gpt4 book ai didi

java - broadcastReceiver 无法根据通知工作(pendingIntent)

转载 作者:行者123 更新时间:2023-11-30 03:27:24 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

关于java - broadcastReceiver 无法根据通知工作(pendingIntent),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18026986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com