应用程序在通知点击后从后台打开后运行功能

我对 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);

}


慕标琳琳
浏览 90回答 2
2回答

婷婷同学_

您可以传递带有通知 PendingIntent 的警报消息。在 PendingIntent .putExtra() 中添加要显示为警报的消息或值,并在 PendingIntent 中指定要以对话框或任何形式显示警报的活动。 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      }    }

当年话下

您应该在 MainActivity 上使用 onCreate 函数 添加此代码来分解您的意图: Intent receivedIntent = getIntent();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java