0

我試圖在屏幕開啓或關閉時收到通知。我註冊了一個廣播接收器,如下所示。廣播接收不顯示通知

但是當我按下邊緣右上角的按鈕時,接收器被調用,但代碼中顯示的日誌語句不顯示。

請告訴我知道改正它

代碼

@Override 
public void onReceive(Context context, Intent intent) { 
    // TODO Auto-generated method stub 
    String action = intent.getAction(); 

    switch (action) { 

    case Intent.ACTION_SCREEN_ON: 
     Log.w(TAG, SubTag.msg("onReceive", "Intent.ACTION_SCREEN_ON")); 
     break; 
    case Intent.ACTION_SCREEN_OFF: 
     Log.w(TAG, SubTag.msg("onReceive", "Intent.ACTION_SCREEN_OFF")); 
     break; 

    default: 
     Log.w(TAG, SubTag.msg("onReceive", "UNHANDLED CASE")); 
     break; 
    } 
} 

更新

我registerd的rceiver處理通信如下:

registerReceiver(this.mScreenReceiver, new IntentFilter(intent.ACTION_SCREEN_ON)) 

registerReceiver(this.mScreenReceiver,new IntentFilter(intent.ACTION_SCREEN_OFF))

+0

您是否在清單中註冊接收器? 'Log'也不會出現在屏幕上,也許你想用烤麪包。 – SaNtoRiaN

+0

@SaNtoRiaN你是否有權限?不,我沒有添加任何permssions。我是不是該?請讓我知道哪一個 – user2121

+0

@ user2121,你有沒有嘗試過Log.d而不是Log.w(可能我只是在首選項中看不到Log.w)?必須嘗試通過調試斷點捕捉'onRecieve'? – Vyacheslav

回答

1

這不是一個許可,你應該在清單中註冊你的廣播。在清單中application標籤內,寫這樣的代碼,但首先將名稱更改爲你的廣播類名

<receiver android:name=".your_class_name_here" > 
    <intent-filter> 
     <action android:name="android.intent.action.SCREEN_OFF" /> 
     <action android:name="android.intent.action.SCREEN_ON" /> 
    </intent-filter> 
</receiver> 

更新 試試這個廣播

private BroadcastReceiver ScreenActions = new BroadcastReceiver() { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.i("BroadcastReceiver", "Broadcast is called"); 

     if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { 
      Log.i("BroadcastReceiver", "Screen ON"); 
     } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { 
      Log.i("BroadcastReceiver", "Screen OFF"); 
     } 

    } 
}; 

和裏面的onStart()註冊它

registerReceiver(ScreenActions, new IntentFilter(Intent.ACTION_SCREEN_ON)); 
registerReceiver(ScreenActions, new IntentFilter(Intent.ACTION_SCREEN_OFF)); 
+0

好吧,但我是alos使用藍牙,我還沒有註冊它的清單,它工作正常!我註冊我的接收器onStart() – user2121

+0

@ user2121是的,你可以做兩種方法之一,在清單或onStart(),但重要的是註冊它 – SaNtoRiaN

+0

所以我註冊的屏幕接收器onstart(),它不是正在工作 – user2121