在启动时的Andr​​oid的BroadcastReceiver [英] Android BroadcastReceiver on startup

查看:180
本文介绍了在启动时的Andr​​oid的BroadcastReceiver的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个应用程序来监控接收短信和我有这样的工作完全符合一个BroadcastReceiver。然而,这是从活动工作,但我想要的BroadcastReceiver来运行所有的时间不只是当我调试的活动正在运行。我怎样才能做到这一点?我已经通过的BroadcastReceiver的生命周期看,但提到的文档中的所有的是,生命周期是有限的的onReceive方法,而不是保持的BroadcastReceiver检查收到的短的生命周期。我怎样才能让这个执着?

I'm writing an app to monitor incoming sms and I have this working perfectly with a BroadcastReceiver. However this is working from an Activity but I'd like the BroadcastReceiver to be running all the time not just when my debug Activity is running. How can I achieve this? I've looked through the lifecycle of the BroadcastReceiver but all that is mentioned in the documentation is that the lifecycle is limited to the onReceive method, not the lifecycle of keeping the BroadcastReceiver checking for incoming sms. How can I make this persistent?

非常感谢,

史蒂夫

推荐答案

您需要定义一个接收器的清单与动作名称 android.intent.action.BOOT_COMPLETED

You need to define a receiver in manifest with action name android.intent.action.BOOT_COMPLETED.

<!-- Start the Service if applicable on boot -->
<receiver android:name="com.prac.test.ServiceStarter">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

确认还包含完整的引导权限。

Make sure also to include the completed boot permission.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

使用服务为此做任何事情存在。并用接收器来接收引导up事件再次重新启动该服务,如果系统启动。

Use Service for this to make anything persist. And use receivers to receive Boot Up events to restart the service again if system boots..

code为在启动时启动服务。使服务做你检查的短信或任何你想要的工作。你需要做你的工作 MyPersistingService 定义它你自己。

Code for Starting Service on boot up. Make Service do your work of checking sms or whatever you want. You need to do your work in MyPersistingService define it your self.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ServiceStarter extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent("com.prac.test.MyPersistingService");
        i.setClass(context, MyPersistingService.class);
        context.startService(i);
    }
}

这篇关于在启动时的Andr​​oid的BroadcastReceiver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆