[英]Android broadcast receiver (screen) not working on Moto g
我正在嘗試捕獲Moto G手機上的屏幕開/關事件。 主要活動有
Intent intentscreen = new Intent(getApplicationContext(), ScreenService.class);
startService(intentscreen);
其中“ ScreenService”如下所示:
public int onStartCommand(Intent intent, int flags, int startId)
{
if (intent!=null)
{
super.onCreate();
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock");
if(!wifiLock.isHeld()){
wifiLock.acquire();
}
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
registerReceiver(this.mybroadcast, filter);
return super.onStartCommand(intent, flags, startId);
}
return START_STICKY;
}
@Override
public void onDestroy()
{
super.onDestroy();
unregisterReceiver(mybroadcast);
if(wifiLock.isHeld()){
wifiLock.release();
}
}
而接收器類如下所示:
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Screen", "--- I Fire!");
}
}
清單文件具有權限,但問題是我的手機在最初的幾個小時內收到了該事件,然后停止接收,即Log.d("Screen", "--- I Fire!");
未顯示在我的日志貓中。
另外還要補充一點,如果我獲得PowerManager.WakeLock wakeLock
不起作用,但是如果我獲得WifiLock wifiLock = null
,這可以工作幾個小時,那么關於如何保持Wifi處於活動狀態的任何建議?
有什么建議可能是錯的嗎? 還是我應該獲得其他任何類型的鎖? 我不想為鎖使用大量電池。
如果您的服務由於內存不足而被系統殺死,則稍后將以意圖傳遞的null重啟該服務。 發生這種情況時,您將失去廣播接收器,因為如果intent為null,則您什么也不做。
似乎無法從android清單中的靜態接收器獲取這些廣播。 因此,您可能必須保留服務。
遵循以下原則:
public void onCreate (){
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
registerReceiver(mybroadcast, filter);
}
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}
@Override
public void onDestroy()
{
super.onDestroy();
unregisterReceiver(mybroadcast);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.