如果我通过getBroadcast(someArgs)创建PendionIntent,BroadCastReceiver不起作用; 但如果我通过getServie()创建并在onStartCommand()中捕获事件,那么它可以正常工作
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);
}
}
答案 0 :(得分:1)
您的BroadcastReceiver是onCreate()方法中的局部变量。退出该方法块后,没有任何东西保留在BroadcastReceiver上,它将被垃圾收集。
您应该创建一个单独的类来扩展BroadcastReceiver并在AndroidManifest.xml中声明它。
<application ...
...
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="someAction" />
</intent-filter>
</receiver>
</application>