Search code examples
androidandroid-intentbroadcastreceiverandroid-broadcast

broad cast receive does not show notifications


i am trying to receive notifications when the screen goes on or off. i registered a broad cast receiver as shown below.

but when i press the button on the top right on the edge, the receiver is called but the log statements shown in the code does not show.

please tell me know to correct it

code:

@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;
    }
}

update:

i registerd the rceiver in onstart as follows:

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

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


Solution

  • It's not a permission, you should register your broadcast in the manifest. Inside the application tags in the manifest, write this code but first change the name to your broadcast class name

    <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>
    

    Update Try this broadcast

    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");
            }
    
        }
    };
    

    and inside your onStart() register it

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