[转] Android 检测电源按钮是否被按下

原文地址:[url]https://stackoverflow.com/a/30030372[/url]

在 AndroidManifest.xml 文件中追加如下代码:





在 MainActivity.java 中追加如下代码,启动 Service:
startService(new Intent(this, LockService.class));

[b]LockService.java[/b]
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://stackoverflow.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;
}
}
}

[b]ScreenReceiver.java[/b]
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.stackoverflow.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setData(Uri.parse(url));
context.startActivity(i);
}
}
}

你可能感兴趣的:(Android)