如何在屏幕解锁时启动应用程序?

How to launch an app when the screen unlocks?

我试过这段代码,但它不起作用。有人有不同的解决方案吗?我已经尝试了很多方法,例如 Stack Overflow 中的以下方法,但其中 none 有效。

manifest.xml

 <receiver android:name=".ScreenReceiver">
 <intent-filter>
 <action android:name="android.intent.action.SCREEN_OFF"/>
 <action android:name="android.intent.action.SCREEN_ON"/>
 </intent-filter>
 </receiver>

屏幕接收器

  public class ScreenReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
         if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
         {
            Intent intent = new Intent();  
            intent.setClass(context, ScreenLockActivity.class);
            startActivity(intent);          
         }
    }
}

要收听屏幕 on/off,您的应用应按时间 运行 并以编程方式将 Broadcast receiver 注册到 OS。

ScreenOnOffService.java

public class ScreenOnOffService extends Service {

    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onCreate() {
        super.onCreate();
        Log.i("ScreenOnOffService", "onCreate: ");
        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction("android.intent.action.SCREEN_OFF");
        intentFilter.addAction("android.intent.action.SCREEN_ON");
        registerReceiver(ScreenOnReceiver.newInstance(), intentFilter);
    }

    public void onDestroy() {
        super.onDestroy();
        Log.i("ScreenOnOffService", "onDestroy: ");
        unregisterReceiver(ScreenOnReceiver.newInstance());
//        startService(new Intent(this,ScreenOnOffService.class));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_STICKY;
    }

}

ScreenOnReceiver.java

public class ScreenOnReceiver extends BroadcastReceiver {

    public static final String TAG = "ScreenOn";
    public static volatile ScreenOnReceiver screenOn;

    public static ScreenOnReceiver newInstance() {
        if (screenOn == null) {
            screenOn = new ScreenOnReceiver();
        }
        return screenOn;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("hieuN", "intent: " + intent.getAction());
        // do work. start activity.

    }
}

activity开始服务

Intent service = new Intent(this, ScreenOnOffService.class);
startService(service);