【问题标题】:broadcastReceiver doesn't work from notification (pendingIntent)BroadcastReceiver 不能从通知中工作(pendingIntent)
【发布时间】:2013-08-02 22:23:04
【问题描述】:

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

【问题讨论】:

    标签: java android service notifications broadcastreceiver


    【解决方案1】:

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

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

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

    【讨论】:

    • 我将数据从服务发送到活动,并在我的代码示例中创建了 broadcastReseiver 并且它可以工作,为什么在服务中它不起作用?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多