新增一个Application类 (源代码复制粘贴即可,甚至不需要理解直接看最后的使用例子就够了。我不像其他人源代码还需要另外下载收积分,大家直接复制粘贴就能用)
public class MainApplication extends Application {
private static MainApplication mApp;
private LockScreenReceiver mReceiver;
private String mChange = "";
public static MainApplication getInstance() {
return mApp;
}
public String getChangeDesc() {
return mApp.mChange;
}
public void setChangeDesc(String change) {
mApp.mChange = change;
}
@Override
public void onCreate() {
super.onCreate();
mApp = this;
mReceiver = new LockScreenReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mReceiver, filter);
}
private class LockScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String change = "";
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
change = "亮屏";
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
change = "锁屏";
} else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
change = "解锁";
}
MainApplication.getInstance().setChangeDesc(change);
}
}
}
}
在androidmanifest.xml中的application下声明name为上面新增的类
android:name=".MainApplication"
最后直接在代码中调用即可,比如我需要锁屏的时候不把我程序的线程池关闭
@Override
protected void onDestroy() {
if (MainApplication.getInstance().getChangeDesc() == "锁屏") {
//锁屏会调用onDestroy和onStop,在这里面判断不执行关闭线程池
}else {
//除了锁屏之外会调用onDestroy只有三种可能:关机,退出程序,杀死进程
//else如果是其他情况调用onDestroy,就把线程池关闭
if (mThreadPoolExecutor.isTerminated() != true) {
mThreadPoolExecutor.shutdown();
}
}
super.onDestroy();
}