我收到了一封来自服务的通知。我想在通知点击时再次呼叫该服务。但是通知点击无法进入方法。
Intent intent = new Intent(this, MyService.class).setAction(ACTION_1);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.food)
.setContentTitle("notification")
.setContentText("near by you!");
NotificationManager mNotificationManager =(NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
我想要调用的方法是
if (ACTION_1.equals(resultPendingIntent)) {
getRecommendation();
}
mBuilder.setContentIntent(resultPendingIntent);
mNotificationManager.notify(id, mBuilder.build());
我试过以下链接但无法解决我的问题。 How to execute a method by clicking a notification
答案 0 :(得分:8)
您可以在Broadcast
中指定Service
,并通过通知中的PendingIntent
启动该广告。
Intent stopIntent = new Intent("my.awersome.string.name");
PendingIntent stopPi = PendingIntent.getBroadcast(this, 4, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT);
然后,在通知构建器中:
NotificationCompat.Builder builder;
builder = new NotificationCompat.Builder(context)
...
.setContentIntent(stopPi);
在您的Service
中,您可以将BroadcastReceiver
设置为:
private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Code to run
}
};
您只需使用以下内容在receiver
(可能在Service
)中注册此onStartCommand()
:
registerReceiver(myReceiver, new IntentFilter("my.awersome.string.name"));
你的Service
必须正在运行才能发挥作用。
答案 1 :(得分:0)
更好的选择是尝试How to execute a method by clicking a notification ..但是因为静态类
而要小心