Подтвердить что ты не робот

Запуск приложения, только если он не запущен

Я отправляю push-уведомление пользователям, которые при нажатии на него открывают приложение.

Моя проблема в том, что, когда приложение уже открыто, нажатие на уведомление снова запустит приложение.

Мне нужно только запустить приложение, если оно еще не запущено.

В уведомлении используется ожидающее намерение:

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Splash.class), 0);

Я видел сообщения, которые говорят:

<activity 
android:name=".Splash"
android:launchMode="singleTask"

но дело в том, что в моем запущенном приложении работает другая активность, а затем всплытие, которое завершается через 7 секунд после запуска приложения, поэтому, когда приложение работает, Splash не является текущей деятельностью.

4b9b3361

Ответ 1

Используйте "запуск Intent" для своего приложения, например:

PackageManager pm = getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage("your.package.name");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, launchIntent, 0);

Замените "your.package.name" на имя вашего пакета из манифеста Android.

Кроме того, вы должны удалить специальный launchMode="singleTask" из вашего манифеста. Стандартное поведение Android будет делать то, что вы хотите.

Ответ 2

String appPackageName = "";

private void isApplicationInForeground() throws Exception {
    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        final List<ActivityManager.RunningAppProcessInfo> processInfos = am
                .getRunningAppProcesses();
        ActivityManager.RunningAppProcessInfo processInfo = processInfos
                .get(0);
        // for (ActivityManager.RunningAppProcessInfo processInfo : processInfos) {
        if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            // getting process at 0th index means our application is on top on all apps or currently open 
            appPackageName = (Arrays.asList(processInfo.pkgList).get(0));
        }
        // }
    }
    else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = null;
        componentInfo = taskInfo.get(0).topActivity;
        appPackageName = componentInfo.getPackageName();
    }
}

private void notifyMessage(String text) {
    if (appPackageName.contains("com.example.test")) {
        // do not notify
    }
    else {          
        // create notification and notify user  
    }
}

Ответ 3

Вместо того, чтобы показывать активность Splash при уведомлении, покажите свою MainActivity, потому что ваша активность всплеска будет закрыта через некоторое время, но MainActivity останется открытым и

<activity 
android:name=".MainActivity"
android:launchMode="singleTask"

Ответ 4

Используйте Splash as Fragment вместо Activity. Храните фрагмент Splash (7 секунд), замените его на желаемую (целевую страницу).

Добавьте в манифест launch launchMode = "singleTask".

Как уже было сказано Rahul, onNewIntent() вызывается, если приложение уже работает else onCreate()

@Override
protected void onNewIntent(Intent intent) 
{   
    super.onNewIntent(intent);
}

ИЛИ

Пойдите с ответом David, кажется многообещающим.

Ответ 5

Для тех, кто использует Xamarin.Android. Ниже приведена версия ответа Дэвида Вассера Xamarin:

        //Create notification
        var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
        Intent uiIntent = PackageManager.GetLaunchIntentForPackage("com.company.app");

        //Create the notification
        var notification = new Notification(Android.Resource.Drawable.SymActionEmail, title);

        //Auto-cancel will remove the notification once the user touches it
        notification.Flags = NotificationFlags.AutoCancel;

        //Set the notification info
        //we use the pending intent, passing our ui intent over, which will get called
        //when the notification is tapped.
        notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, PendingIntentFlags.OneShot));

        //Show the notification
        notificationManager.Notify(0, notification);

Ответ 6

при нажатии на уведомление, а ваш код, который перенаправляется на экран желаний, просто заменяет этот код, вызывая этот метод и перенаправляя его на конкретный экран на основе "истинного/ложного" результата.

    private boolean isAppOnForeground(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
    if (appProcesses == null) {
      return false;
    }
    final String packageName = context.getPackageName();
    for (RunningAppProcessInfo appProcess : appProcesses) {
      if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
        return true;
      }
    }
    return false;
  }

Ответ 7

Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT

И, возможно, не запускайте активность Splash и не открывайте (довести до конца) MainActivity и не обновите пользовательский интерфейс слушателем, который сообщает вам, что у вас есть новое уведомление (с флагом - логическое или с интерфейсом, чтобы сделать слушатель).

Ответ 8

Вы можете использовать упорядоченную трансляцию для выполнения этого.

1) Измените PendingIntent, чтобы запустить BroadcastReceiver, который решит, начать ли это действие или ничего не делать:

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, DecisionReceiver.class), 0);

2) Создайте решение BroadcastReceiver:

public class DecisionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        context.sendOrderedBroadcast(new Intent(MainActivity.NOTIFICATION_ACTION), null, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (getResultCode() == MainActivity.IS_ALIVE) {
                    // Activity is in the foreground
                }
                else {
                    // Activity is not in the foreground
                }
            }
        }, null, 0, null, null);
    }
}

3) Создайте BroadcastReceiver в своей активности, который будет сигнализировать о том, что он жив:

public static final String NOTIFICATION_ACTION = "com.mypackage.myapplication.NOTIFICATION";
public static final int IS_ALIVE = 1;
private BroadcastReceiver mAliveReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        setResultCode(IS_ALIVE);
    }
};

// Register onResume, unregister onPause
// Essentially receiver only responds if the activity is the foreground activity
@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mAliveReceiver, new IntentFilter(NOTIFICATION_ACTION));
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mAliveReceiver);
}

Ответ 9

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

notificationIntent.putExtras(bundle);
PendingIntent pintent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Ответ 10

попробуйте добавить это к вашему намерению перенести активность на передний план, если она работает в фоновом режиме

Intent intent = new Intent(this, Splash.class); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);

Ответ 11

прежде всего задайте заданную по умолчанию задачу android:taskAffinity="com.example.testp.yourPreferredName" в элементе Application в файле манифеста. Сохраните android:launchMode="singleTask" на SplashActivity. Теперь, когда ваша SplashActivity является вашей основной записью, добавьте этот код как к onResume(), onNewIntent(), так и к onCreate() (вторая мысль onResume() не рекомендуется) - следуйте комментариям в коде

//Note these following lines of code will work like magic only if its UPVOTED.
//so upvote before you try it.-or it will crash with SecurityException
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);

List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1000);    
    for(int i =0; i< taskInfo.size(); i++){
        String PackageName = taskInfo.get(i).baseActivity.getPackageName();
        if(PackageName.equals("packagename.appname")){// suppose stackoverflow.answerer.Elltz
            //if the current runing actiivity is not the splash activity. it will be 1
            //only if this is the first time your <taskAffinity> is be called as a task
            if(taskInfo.get(i).numActivities >1){
                //other activities are running, so kill this splash dead!! reload!!                 
                finish();
                // i am dying in onCreate..(the user didnt see nothing, that the good part)
                //about this code. its a silent assassin
            }
            //Operation kill the Splash is done so retreat to base.
            break;
        }
    }

Этот код не будет работать на api 21+; для его работы вам нужно использовать AppTask, это избавит вас от лишних строк кода, поскольку вы не будете в Loop, чтобы найти свой Task.

Надеюсь, что это поможет