我遇到了同样的情况,我设法通过创建一个在按下操作按钮时调用的广播接收器来解决它。然后,广播接收器会收到一个带有您要关闭的通知 ID 和您要拨打的号码的意图。
这是创建通知的代码:
NotificationManager notificationManager =
(NotificationManager)MyApplication.getAppContext().getSystemService(Context.NOTIFICATION_SERVICE);
//for some versions of android you may need to create a channel with the id you want
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel chan = new NotificationChannel("your_channel_id", "ChannelName", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(chan);
}
Intent intent = new Intent(MyApplication.getAppContext(), ActionReciever.class);
intent.putExtra("phoNo", phoneNumber);
// num is the notification id
intent.putExtra("id", num);
PendingIntent myPendingIntent = PendingIntent.getBroadcast(
MyApplication.getAppContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT
);
Notification n = new NotificationCompat.Builder(MyApplication.getAppContext(),
"your_channel_id")
.setSmallIcon(R.drawable.app_pic)
.addAction(R.drawable.app_pic, "Dial now", myPendingIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(num, n);
这是广播接收器代码,在按下操作按钮时调用。这里接收到的intent就是我们在通知中准备的pending intent里面的intent:
public class ActionReciever extends BroadcastReceiver {
@SuppressLint("MissingPermission")
@Override
public void onReceive(Context context, Intent intent) {
String phoneNumber = intent.getStringExtra("phoNo");
int id = intent.getIntExtra("id",0);
Intent i = new Intent(Intent.ACTION_DIAL);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setData(Uri.parse("tel:" + phoneNumber));
NotificationManager notificationManager =
(NotificationManager) MyApplication.getAppContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(id);
context.startActivity(i);
}
}
在应用程序标签内的应用程序清单中注册广播接收器
<receiver android:name=".ActionReciever" />
MyApplication 是一个扩展默认应用程序的类,因此我可以有一个地方来存储我需要的上下文。
public class MyApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
请注意,您需要更新清单以运行 MyApplication 类,如下所示:
android:name="com.example.yourpackage.MyApplication"
即使应用程序关闭且没有后台服务,此代码也能正常工作。