Android 单击通知未开始预期活动?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20743998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:23:36  来源:igfitidea点击:

Clicking on Notification is not starting intended activity?

androidgoogle-cloud-messagingandroid-notifications

提问by user818455

I am using GCM in my application and also using NotificationManager to Create a Notification whenever GCM message is received.Till now everything is working perfectly and GCM message is showing correctly in Notification area, but when I click on the notification it should start an activity of my application which will display the message detail which is not happening. Every-time I click on notification it does not start any activity and it remains as is.My code for creating Notification is :

我在我的应用程序中使用 GCM,并在收到 GCM 消息时使用 NotificationManager 创建通知。到目前为止,一切正常,并且 GCM 消息在通知区域中正确显示,但是当我单击通知时,它应该启动一个活动我的应用程序将显示未发生的消息详细信息。每次我点击通知时,它都不会启动任何活动,并且保持原样。我创建通知的代码是:

private void sendNotification(String msg) {
        SharedPreferences prefs = getSharedPreferences(
                DataAccessServer.PREFS_NAME, MODE_PRIVATE);
        mNotificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent = new Intent(this, WarningDetails.class);
        Bundle bundle = new Bundle();
        bundle.putString("warning", msg);
        bundle.putInt("warningId", NOTIFICATION_ID);
        intent.putExtras(bundle);
        // The stack builder object will contain an artificial back stack for
        // the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(WarningDetails.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(intent);

        PendingIntent contentIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.weather_alert_notification)
                .setContentTitle("Weather Notification")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg);
        String selectedSound = prefs.getString("selectedSound", "");
        if (!selectedSound.equals("")) {
            Uri alarmSound = Uri.parse(selectedSound);
            mBuilder.setSound(alarmSound);

        } else {
            Uri alarmSound = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            mBuilder.setSound(alarmSound);
        }

        if (prefs.getBoolean("isVibrateOn", false)) {
            long[] pattern = { 500, 500, 500, 500, 500, 500, 500, 500, 500 };
            mBuilder.setVibrate(pattern);
        }

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }

I updated my code to support Preserving Navigation when Starting an Activityjust like it happens in Gmail application using the Android developers website since then it stopped working.Someone Please guide me what I am missing or doing wrong in this code.

我更新了我的代码以支持Preserving Navigation when Starting an Activity就像它在使用 Android 开发者网站的 Gmail 应用程序中发生的那样,从那时起它就停止工作了。有人请指导我我在这段代码中遗漏了什么或做错了什么。

回答by user818455

My problem got solved I just have to add PendingIntent.FLAG_ONE_SHOTflag as well , so I replaced :

我的问题解决了,我只需要添加PendingIntent.FLAG_ONE_SHOT标志,所以我替换了:

PendingIntent contentIntent = stackBuilder
                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

to

PendingIntent contentIntent = stackBuilder
                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
                        | PendingIntent.FLAG_ONE_SHOT);

回答by Tony Vu

I encountered the same issue and resolved it by adding android:exported="true"to the activity declaration in AndroidManifest.xml.

我遇到了同样的问题并通过将android:exported="true" 添加到 AndroidManifest.xml 中的活动声明来解决它。

回答by M D

Here you just passed your Intent into pendingintent: see below

在这里,您刚刚将您的 Intent 传递给了 pendingintent:见下文

Intent notificationIntent = new Intent(context, Login.class);

 PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
and set this contentintent into your Notification:

Notification noti = new NotificationCompat.Builder(context)
                    .setSmallIcon(icon_small)
                    .setTicker(message)
                    .setLargeIcon(largeIcon)
                    .setWhen(System.currentTimeMillis())
                    .setContentTitle(title)
                    .setContentText(message)
                    .setContentIntent(**contentIntent**)
                    .setAutoCancel(true).build();

This may help you.

这可能对你有帮助。

回答by Ahmad Muzakki

if you launch the intended activity using Action Stringdont forget to add

如果您使用Action String启动预期的活动,请不要忘记添加

<intent-filter>
       <action android:name="YOUR ACTION STRING"/>
       <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

inside <activity></activity>tag

<activity></activity>标签

回答by Sam Boychuk

The activity that you want to launch has to be designated as a LAUNCHER activity in your manifest - otherwise it won't launch via a Pending Intent. Add the following to your in the AndroidManifext.xml

您要启动的活动必须在清单中指定为 LAUNCHER 活动 - 否则它不会通过挂起的意图启动。将以下内容添加到您的 AndroidManifext.xml 中

<activity
...
android:exported="true">
<intent-filter>
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Otherwise you will need to use an Activity that is already designated as a LAUNCHER (such as your MAIN activity)

否则,您将需要使用已指定为启动器的活动(例如您的主要活动)

回答by AndroidHacker

Do some thing like this on generateNotification() method ..

在 generateNotification() 方法上做一些这样的事情..

Replace your activity with Splash.Java class in it.

用其中的 Splash.Java 类替换您的活动。

/**
     * Issues a notification to inform the user that server has sent a message.
     */
    @SuppressWarnings("deprecation")
    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        //message = "vivek";
       // Log.d("anjan", message.split("~")[0]);
        //Toast.makeText(context, message, Toast.LENGTH_LONG).show();

        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);
        Log.d("anjan1", title);
        String text_message = context.getString(R.string.title_activity_main);
        Log.d("anjan1", text_message);

        Intent notificationIntent = new Intent(context, Splash.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_SOUND;

        // Vibrate if vibrate is enabled
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);      

    }

回答by Yvan RAJAONARIVONY

Try this instead of the last line :

试试这个而不是最后一行:

mNotificationManager.notify(0, mBuilder.getNotification());

mNotificationManager.notify(0, mBuilder.getNotification());