在启动Android的广播接收器

在启动Android的广播接收器

本文介绍了在启动Android的广播接收器 - 继续运行时,活动在后台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我监视传入短信。

我的应用与广播接收器完美的工作。然而,它是从活动的工作,并希望想保持在广播接收器运行所有的时间(不只是当我的活动正在运行)。

My app is working perfectly with a BroadcastReceiver. However it is working from an Activity and would like like to keep the BroadcastReceiver running all the time (and not just when my Activity is running).

我怎样才能做到这一点?我已经通过了广播接收器但就是在文档中提到的所有是生命周期是有限的的onReceive方法,而不是保持的BroadcastReceiver检查的生命周期的生命周期看传入的​​短信。

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"/>

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

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);
    }
}

这篇关于在启动Android的广播接收器 - 继续运行时,活动在后台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:52