启动时的 Android BroadcastReceiver - 当 Activity 处于后台时继续运行 [英] Android BroadcastReceiver on startup - keep running when Activity is in Background

查看:35
本文介绍了启动时的 Android BroadcastReceiver - 当 Activity 处于后台时继续运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在监控收到的短信.

I'm monitoring incoming SMSs.

我的应用与 BroadcastReceiver 完美配合.但是,它是从 Activity 工作的,并且希望让 BroadcastReceiver 一直运行(而不仅仅是在我的 Activity 运行时).

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

我怎样才能做到这一点?我已经查看了 BroadcastReceiver 的生命周期,但文档中提到的只是生命周期仅限于 onReceive 方法,而不是保留 BroadcastReceiver 的生命周期code>BroadcastReceiver 检查传入的 SMS.

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?

谢谢

推荐答案

您需要在清单中定义一个 receiver 操作名称为 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"/>

使用 Service 来保持任何东西.并使用接收器接收启动事件以在系统启动时再次重新启动服务..

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

启动时启动服务的代码.让服务完成您检查短信或任何您想要的工作.您需要在 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 BroadcastReceiver - 当 Activity 处于后台时继续运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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