首页 文章

通知单击:活动已打开

提问于
浏览
139

我有一个带有通知的应用程序,如果我点击它们就会打开某个活动 . 我想要的是,如果我点击通知并且活动已经打开,那么 not 再次启动,但只是被带到了前面 .

我以为我可以用旗帜 FLAG_ACTIVITY_BROUGHT_TO_FRONTFLAG_ACTIVITY_REORDER_TO_FRONT 来做,但它会继续打开它,所以我有两次活动 .

这是我的代码:

event_notification = new Notification(R.drawable.icon,
            mContext.getString(R.string.event_notif_message), System.currentTimeMillis()); 
Intent notificationIntent = new Intent(mContext, EventListActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
sendNotification(event_notification, notificationIntent, mContext.getString(R.string.event_notif_title),
                body, Utils.PA_NOTIFICATIONS_ID);

我可以使用标志管理它,还是应该在SharedPreferences中存储变量以检查它是否已打开?

谢谢!

6 回答

  • 2

    您需要设置 ActivitylaunchMode 属性,您将开始 singleTop . 这将导致传入的Intent传递到现有实例,而不是在 Activity 已经位于任务堆栈顶部时启动新实例 .

    通过将 android:launchMode="singleTop" 添加到 <activity> 元素,可以在清单中完成此操作 . 要访问最新的Intent(如果您对可能传入的任何数据感兴趣),请覆盖 Activity 中的 onNewIntent() .

  • 248

    尝试将标志设置为 Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP .

    来自documentation for FLAG_ACTIVITY_CLEAR_TOP(强调我的):

    如果已设置,并且正在启动的活动已在当前任务中运行,则不会启动该活动的新实例,而是将关闭其上的所有其他活动,并将此Intent传递给(现在在顶部)旧活动作为一个新的意图 . 例如,考虑一个由活动组成的任务:A,B,C,D . 如果D调用带有解析为活动B组件的Intent的startActivity(),则C和D将完成,B接收给定的Intent ,导致堆栈现在为:A,B . 上例中活动B的当前运行实例将在其onNewIntent()方法中接收您从此处开始的新意图,或者本身已完成并使用新意图重新启动 . 如果它已将其启动模式声明为“多个”(默认值)并且您没有在同一意图中设置FLAG_ACTIVITY_SINGLE_TOP,那么它将被完成并重新创建;对于所有其他启动模式或如果设置了FLAG_ACTIVITY_SINGLE_TOP,则此Intent将被传递到当前实例的onNewIntent() .

  • 1

    使用 onNewIntent() 处理来自通知点击的新数据并刷新活动 .

    onNewIntent 中从新意图(由新通知提供服务)中获取新数据并捕获它们,例如:

    title = intent.getStringExtra("title")

    onCreate 之前:)

    它将使用新的通知数据刷新当前活动 .

    您也可以按照本教程:http://androidrace.com/2016/12/10/how-to-refresh-activity-on-new-notification-click-android-developer/

  • 0
    Notification.Builder mBuilder =
                new Notification.Builder(this)
                .setSmallIcon(R.drawable.cmplayer)
                .setContentTitle("CoderoMusicPlayer")
                .setContentText("PLayer0!");
    
        Intent resultIntent = new Intent(this, 
    
        AndroidBuildingMusicPlayerActivity.class);
            resultIntent.setAction(Intent.ACTION_MAIN);
            resultIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                    resultIntent, 0);
    
            mBuilder.setContentIntent(pendingIntent);
            NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            mNotificationManager.notify(1, mBuilder.build());
    

    只需复制代码并将其粘贴到主启动器活动中即可 .

    Here is Original Answer

  • 34
    Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, new Random().nextInt(), intent, 0);
    
  • 4

    我认为你应该添加一些逻辑来使它工作,也许这可以帮助:

    For example I have a Splash Screen (Launcher and MAIN) of APP:

    public class SplashScreen extends AppCompatActivity {
        private final int TIME_OUT = 2000;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_splash_screen);
    
            // Suscribirse al tema Notificaciones
            FirebaseMessaging.getInstance().subscribeToTopic("NOTA");
            if (getIntent().getExtras() != null) {
                if (getIntent().getExtras().size()>1){
                    Intent home_activity = new Intent(getApplicationContext(), Home.class);
                    home_activity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    if (getIntent().getExtras() != null) {
                        for (String key : getIntent().getExtras().keySet()) {
                            String value = "" + getIntent().getExtras().getString(key);
                            Log.d("TAG", key + "=" + value);
                            switch (key) {
                                case "url":
                                    home_activity.putExtra("url", value);
                                    break;
                            }
                        }
                    }
                    startActivity(home_activity);
                    finish();
    
                }else{
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Intent home_activity = new Intent(getApplicationContext(), Home.class);
                                home_activity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(home_activity);
                                finish();
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }, TIME_OUT);
                }
    
    
            } else {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Intent home_activity = new Intent(getApplicationContext(), Home.class);
                            home_activity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(home_activity);
                            finish();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }, TIME_OUT);
            }
    
        }
    
    }
    

    And in my FirebaseService I have done the following:

    public class FCMessagingService extends FirebaseMessagingService {
    
        private final String TAG = "PUSH";
        private String body = "";
        private static String _url = "";
        private static int numMessage = 0;
    
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            super.onMessageReceived(remoteMessage);
    
            String from = remoteMessage.getFrom();
            Log.d(TAG, "Mensaje recibido de: " + from);
    
            if (remoteMessage.getNotification() != null) {
                Log.d(TAG, "Notificación: " + remoteMessage.getNotification().getBody());
    
                if (remoteMessage.getData().size() > 0) {
                    Log.d(TAG, "Data: " + remoteMessage.getData());
                    try {
                        JSONObject data = new JSONObject(remoteMessage.getData());
                        String url = data.getString("url");
                        Log.d(TAG, "onMessageReceived: \n" + "Extra Information: " + url);
                        this._url = url;
                        Log.d("_URL",_url);
                        mostrarNotificacion(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
                        mensaje(url, remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
    
    
    
        }
    
    
        private void mensaje(String url, String title, String body){
            boolean acti =  Util.comprobarActivityALaVista(getApplicationContext(), "com.dev.android.subagan.MainActivity");
            if(acti){
    
                Intent imain = new Intent(MainActivity.URL);
    
                imain.putExtra("key_url",url);
                imain.putExtra("key_title",title);
                imain.putExtra("key_body",body);
    
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(imain);
    
            }else{
    
                Intent ihome = new Intent(Home.URL);
    
                ihome.putExtra("key_url",url);
                ihome.putExtra("key_title",title);
                ihome.putExtra("key_body",body);
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(ihome);
    
            }
    
        }
    
    
    
    
        private void mostrarNotificacion(String title, String body) {
    
            final int NOTIFICATION_ID = 3000;
    
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("url",_url);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    
    
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT  );
    
    
    
            Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setAutoCancel(true)
                    .setSound(soundUri)
                    .setTicker(body)
                    .setContentIntent(pendingIntent);
    
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, notificationBuilder.build());
    
        }
    
    }
    

相关问题