我想在Android中關閉屏幕時收到廣播。我寫了下面的代碼。這是Receiver的代碼。屏幕接收器廣播不工作
@Override
public void onReceive(Context context, Intent intent) {
helper = new FeedReaderDBHelper(context);
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
System.out.println("Screen Off Receiver just received something");
if(helper.getValue(FeedReaderContract.FeedEntry.onlock).equals("YES"))
{
helper.lockAll();
wasScreenOn = false;
}
else if(helper.getValue(FeedReaderContract.FeedEntry.onLock3).equals("YES"))
{
System.out.println("Running 3 minutes thread");
Runner runner = new Runner(context);
Thread t = new Thread(runner);
t.setName("LockThreeThread");
t.start();
}
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
wasScreenOn = true;
}
}
我正在註冊和註銷Receiver in a Service。代碼如下。
在註冊接收機中onStartCommand方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
isScreenOn = pm.isScreenOn();
RegisterReceiver();
//Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_SHORT).show();
//System.out.println("StartRemove");
helper = new FeedReaderDBHelper(this);
names = helper.getNames();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
startChecker();
}
});
t.start();
return START_STICKY;
}
這是我在服務方法的的onDestroy如何取消註冊。
private void RegisterReceiver()
{
receiver = Factory.getScreeReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(receiver, filter);
}
請讓我知道可能是什麼問題。我一直在深入挖掘它。最後兩天浪費在這個上面。似乎沒有任何工作。
使用背景顏色與阿爾法 –
你從哪裏開始服務?服務開始運行的活動是什麼? –
@TharakaDevinda我從主要活動開始服務,是活動和服務正在運行。 –