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

应用启动后,我需要一直保持广播接收器始终运行。


这是在应用程序中注册此接收器的代码


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

        }

     }

}



子衿沉夜
浏览 311回答 3
3回答

小唯快跑啊

您可以使用服务在主应用中启动/停止服务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); }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java