Reputation: 69
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);
}
}
Upvotes: 1
Views: 890
Reputation: 38605
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>
Upvotes: 1