Search code examples
javaandroidservicenotificationsbroadcastreceiver

broadcastReceiver doesn't work from notification (pendingIntent)


BroadCastReceiver doesn't work if i create PendionIntent by getBroadcast(someArgs); but if i create by getServie() and catch event in onStartCommand() it work fine

public class someClass extends Service
{
    Notification createNotif()
    {
        RemoteViews views = new RemoteViews(getPackageName(),R.layout.notif);
        ComponentName componentName = new ComponentName(this,someClass.class);
        Intent intentClose = new Intent("someAction");
        intentClose.setComponent(componentName);
        views.setOnClickPendingIntent(R.id.notifClose, PendingIntent.getBroadcast(this, 0, intentClose, PendingIntent.FLAG_UPDATE_CURRENT));
        Notification notification = new Notification();
        notification.contentView = views;
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        return notification;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
        {

            @Override
            public void onReceive(Context context, Intent intent)
            {
               if(intent.getAction().equals("someAction"))
                  someMethod();
            }
        };
        IntentFilter intentFilter = new IntentFilter("someAction");
        intentFilter.addAction("anyAction");
        registerReceiver(broadcastReceiver,intentFilter);
    }
}

Solution

  • Your BroadcastReceiver is a local variable inside the onCreate() method. Once you exit that method block, there is nothing holding on to the BroadcastReceiver and it will be garbage collected.

    You should instead create a separate class that extends BroadcastReceiver and declare it in your AndroidManifest.xml.

    <application ...
        ...
        <receiver android:name=".MyReceiver" >
            <intent-filter>
                <action android:name="someAction" />
            </intent-filter>
        </receiver>
    </application>