-2
當應用程序正在運行時,我能夠接收屏幕狀態,但是當應用程序停止時,我無法接收它。Android如何在屏幕開啓時接收廣播
這裏我的代碼的LockService
public class LockService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
Log.e("Action","Screen");
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
Log.e("Sample","Screen");
return super.onStartCommand(intent, flags, startId);
}
public class LocalBinder extends Binder {
LockService getService() {
return LockService.this;
}
}
}
廣播接收器
public class ScreenReceiver extends BroadcastReceiver {
Intent intent;
@Override
public void onReceive(final Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.e("Screen state"," ON");
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
MainActivity在OnCreate活動
startService(new Intent(getApplicationContext(), LockService.class));
的Manifest.xml
<service android:name=".LockService">
<intent-filter>
<action android:name="android.intent.action.ACTION_SCREEN_ON"/>
<action android:name="android.intent.action.ACTION_SCREEN_OFF"/>
<action android:name="android.intent.action.ACTION_USER_PRESENT"/>
</intent-filter>
</service>
我想,當用戶喚醒電話
嗨,看看這個問題和答案。 http://stackoverflow.com/q/13307565/5241603 –
即使應用程序停止工作嗎? – KidPPAP
該鏈接僅在應用程序運行時纔有效 – KidPPAP