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

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

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

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

}

}

}

回答:

你可以使用服务

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

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

}

}

以上是 Java 关闭应用程序后,保持广播接收器运行 的全部内容, 来源链接: utcz.com/qa/402317.html

回到顶部