我需要讓應用程序啓動後廣播接收器始終運行。關閉應用程序後繼續運行廣播接收器
下面是在應用程序
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");
}
}
}
您可能想要創建一個[服務](https://developer.android.com/reference/android/app/Service.html) –
但接收事件呢? –
你真的需要監視屏幕開/關事件嗎?他們強迫你註冊一個不在清單中的接收者的原因是他們不希望人們總是監視這些事件並放慢設備速度。 – natez0r