[转] Android 检测电源按钮是否被按下
程序员文章站
2022-05-21 10:21:54
...
原文地址:https://*.com/a/30030372
在 AndroidManifest.xml 文件中追加如下代码:
在 MainActivity.java 中追加如下代码,启动 Service:
LockService.java
ScreenReceiver.java
在 AndroidManifest.xml 文件中追加如下代码:
<service android:name="com.example.userpresent.LockService"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </service>
在 MainActivity.java 中追加如下代码,启动 Service:
startService(new Intent(this, LockService.class));
LockService.java
package com.example.userpresent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.IntentFilter; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; // https://*.com/a/30030372 public class LockService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @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); final BroadcastReceiver mReceiver = new ScreenReceiver(); registerReceiver(mReceiver, filter); return super.onStartCommand(intent, flags, startId); } public class LocalBinder extends Binder { LockService getService() { return LockService.this; } } }
ScreenReceiver.java
package com.example.userpresent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; public class ScreenReceiver extends BroadcastReceiver { public static boolean wasScreenOn = true; @Override public void onReceive(final Context context, final Intent intent) { Log.e("LOB","onReceive"); if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { // do whatever you need to do here wasScreenOn = false; Log.e("LOB","wasScreenOn"+wasScreenOn); } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { // and do whatever you need to do here wasScreenOn = true; }else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){ Log.e("LOB","userpresent"); Log.e("LOB","wasScreenOn"+wasScreenOn); String url = "http://www.*.com"; Intent i = new Intent(Intent.ACTION_VIEW); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setData(Uri.parse(url)); context.startActivity(i); } } }