Android屏幕开启时如何接收广播

时间:2017-05-09 04:55:40

标签: android android-service android-broadcastreceiver

我在应用程序运行时能够接收屏幕状态,但是当应用程序停止时我无法接收它。

这里是我的代码 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);
    }
}
}
onCreate活动中的

MainActivity

 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>

我想在用户唤醒手机时启动一项活动

1 个答案:

答案 0 :(得分:0)

我的代码有效。只是我的手机不稳定,我重新格式化我的手机,然后我的应用程序完美。谢谢你的奉献。

电话:小米米5 操作系统:Android 6.0