为了账号安全,请及时绑定邮箱和手机立即绑定

关闭应用程序后,保持广播接收器运行

关闭应用程序后,保持广播接收器运行

子衿沉夜 2019-12-17 13:11:24
应用启动后,我需要一直保持广播接收器始终运行。这是在应用程序中注册此接收器的代码    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);    filter.addAction(Intent.ACTION_SCREEN_OFF);    BroadcastReceiver mReceiver = new ScreenEventsReceiver();    registerReceiver(mReceiver, filter);和接收器代码public class ScreenEventsReceiver extends BroadcastReceiver {     public static boolean wasScreenOn = true;     @Override     public void onReceive(Context context, Intent intent) {        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {            wasScreenOn = false;            Log.d("ScreenEventReceiver", "ON");        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {            wasScreenOn = true;            Log.d("ScreenEventReceiver", "ON");        }     }}
查看完整描述

3 回答

?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

您可以使用服务


在主应用中启动/停止服务


Intent service = new Intent(context, MyService.class);

context.startService(service);

...

Intent service = new Intent(context, MyService.class);

context.stopService(service);

服务


public class MyService extends Service

{

 private static BroadcastReceiver m_ScreenOffReceiver;


 @Override

 public IBinder onBind(Intent arg0)

 {

  return null;

 }


 @Override

 public void onCreate()

 {

  registerScreenOffReceiver();

 }


 @Override

 public void onDestroy()

 {

  unregisterReceiver(m_ScreenOffReceiver);

  m_ScreenOffReceiver = null;

 }


 private void registerScreenOffReceiver()

 {

  m_ScreenOffReceiver = new BroadcastReceiver()

  {

   @Override

   public void onReceive(Context context, Intent intent)

   {

     Log.d(TAG, "ACTION_SCREEN_OFF");

     // do something, e.g. send Intent to main app

   }

  };

  IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);

  registerReceiver(m_ScreenOffReceiver, filter);

 }

}



查看完整回答
反对 回复 2019-12-17
  • 3 回答
  • 0 关注
  • 310 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信