1

如果我通过 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);
    }
}
4

1 回答 1

1

您的 BroadcastReceiver 是 onCreate() 方法中的一个局部变量。退出该方法块后,BroadcastReceiver 将没有任何保留,它将被垃圾收集。

您应该创建一个单独的类来扩展 BroadcastReceiver 并在您的 AndroidManifest.xml 中声明它。

<application ...
    ...
    <receiver android:name=".MyReceiver" >
        <intent-filter>
            <action android:name="someAction" />
        </intent-filter>
    </receiver>
</application>
于 2013-08-02T22:27:49.487 回答