gpt4 book ai didi

java - 单击通知后从后台打开应用程序后运行函数

转载 作者:行者123 更新时间:2023-12-02 09:50:28 26 4
gpt4 key购买 nike

我对 Android 开发还很陌生。当应用程序在后台运行时,我能够收到弹出的通知。当我单击它时,它成功加载应用程序备份。但是,我想从页面加载警报,但仅当通过通知单击打开警报时才加载。

这是生成通知的代码。任何帮助将不胜感激。

private void getNotificationForPasswordChange() {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Hello";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
if (mNotificationManager != null)
mNotificationManager.createNotificationChannel(mChannel);
}

Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Intent i=new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent mainIntent = PendingIntent.getActivity(this, 0,
i, PendingIntent.FLAG_UPDATE_CURRENT);

Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Pronto Tracker")
.setTicker("Pronto Tracker")
.setContentText("Cannot connect to server. Location is not being updated.")
.setSmallIcon(R.mipmap.ic_pronto_logo)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setOngoing(true).setContentIntent(mainIntent).
build();
mNotificationManager.notify(Constants.PASSWORD_CHANGE_NOTIFICATION_ID, notification);
}

最佳答案

您可以通过通知 PendingIntent 传递警报消息。在 PendingIntent .putExtra() 中添加要显示为警报的消息或值,并在 PendingIntent 中指定要以对话框或其他形式显示警报的 Activity 。

 Intent intent = new Intent(Application.getAppContext(), MainActivity.class);
intent.putExtra("is_notification", true);
intent.putExtra("alert_message", "Hello World!");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_CANCEL_CURRENT);

之后将 PendingIntent 添加到您的通知中。您需要做的第二件事是当用户点击通知时从 Intent 获取数据。在您的 MainActivity 中添加以下代码以从 Intent 获取数据:-

if (getIntent() != null) {
String message = getIntent().getStringExtra("alert_message");
boolean isNotification = getIntent().getBooleanExtra("is_notification", false);

if(is_notification){
// show alert
}
}

关于java - 单击通知后从后台打开应用程序后运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56352766/

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