IT박스

의도-활동이 실행중인 경우이를 앞쪽으로 가져 오거나 그렇지 않으면 알림에서 새 활동을 시작하십시오.

itboxs 2020. 7. 11. 11:08
반응형

의도-활동이 실행중인 경우이를 앞쪽으로 가져 오거나 그렇지 않으면 알림에서 새 활동을 시작하십시오.


내 응용 프로그램에는 플래그가없는 알림이있어 매번 새로운 활동을 시작하므로 여러 개의 동일한 활동이 서로 실행되도록합니다.

내가하고 싶은 것은 알림 보류 의도에 지정된 활동을 이미 실행중인 경우 맨 앞으로 가져오고 그렇지 않으면 시작하는 것입니다.

지금까지 내가 가지고있는 통지의 의도 / 보류 의도는

private static PendingIntent prepareIntent(Context context) {
    Intent intent = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

    return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

이상하게도 때때로 작동하고 때로는 작동하지 않습니다 ... 나는 이미 모든 플래그 조합을 시도한 것처럼 느낍니다.


이것을 사용할 수 있습니다 :

<activity 
   android:name=".YourActivity"
   android:launchMode="singleTask"/>

어느 것과 비슷하게 작동 "singleInstance"하지만 이상한 애니메이션은 없습니다.


나는 그것을하는 가장 좋은 방법은 간단한 방법으로 활동을 정상적으로 시작하는 것이지만 singleInstance속성으로 매니페스트에서 해당 활동을 설정하는 것입니다 . 이를 통해 활동을 항상 앞쪽으로 가져오고 활동이 존재하지 않는 경우 OS가 자동으로 새 것을 만들거나 현재 존재하는 활동을 앞쪽으로 가져 오게하여 현재 두 가지 문제에 실질적으로 접근합니다 ( singleInstance특성).

이것은 활동이 단일 인스턴스로 선언되는 방식입니다.

<activity 
   android:name=".YourActivity"
   android:launchMode="singleInstance"/>

또한 singleInstance를 통해 시작할 때 고르지 못한 애니메이션을 피하기 위해 대신 "singleTask"를 사용할 수 있습니다. 둘 다 매우 비슷하지만 차이점은 여기 Google 문서에 따라 설명되어 있습니다.

<activity 
   android:name=".YourActivity"
   android:launchMode="singleTask"/>

singleInstance는 "singleTask"와 동일하지만 시스템이 인스턴스를 보유하는 작업으로 다른 활동을 시작하지 않는다는 점이 다릅니다. 활동은 항상 태스크의 유일한 유일한 구성원입니다.

도움이 되었기를 바랍니다.

문안 인사!


나는 당신이 필요로하는 singleTop Activity것이 아니라 singleTask또는 안에 있다고 생각합니다 singleInstance.

<activity android:name=".MyActivity"
          android:launchMode="singleTop"
          ...the rest... >

어떤 문서를 말한다 완벽하게 사용자의 요구에 맞게 않습니다 :

[...] singleTop새로운 의도를 처리하기 위해 " "활동 의 새 인스턴스를 만들 수도 있습니다. 그러나 대상 작업에 이미 스택 맨 위에 활동의 기존 인스턴스가있는 경우 해당 인스턴스는 새로운 onNewIntent()호출을 받습니다 ( 통화 중). 새 인스턴스가 작성되지 않습니다. 예를 들어, " singleTop"활동 의 기존 인스턴스가 대상 작업에 있지만 스택의 맨 위에 있지 않은 경우 또는 대상 작업이 아닌 스택의 맨 위에있는 경우-새로운 경우 인스턴스가 생성되어 스택에 푸시됩니다.

그 위에 (장어 의도 없음), 나는 당신과 정확히 같은 필요를 가지고있었습니다. 모든 launchMode플래그를 테스트하여 실제로 실제로 어떻게 동작하는지 파악했으며 결과적 singleTop으로 실제로 가장 적합합니다. 이상한 애니메이션 없음, 최근 응용 프로그램 목록에 앱이 한 번 표시됨 ( singleInstance실제로 인해 두 번 표시되는 것과 달리) (타인 Activity이 그 일의 일부가 될 수 있도록 )하고, 목표가 Activity이미 존재하는지 여부에 관계없이 적절한 행동을 취하십시오 .


이것은 오래된 스레드이지만 여전히 답을 찾고있는 모든 사람들을 위해 여기 내 해결책이 있습니다. 매니페스트 설정없이 순수하게 코드입니다.

private static PendingIntent prepareIntent(Context context) {
  Intent intent = new Intent(context, MainActivity.class);
  intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);      
  return PendingIntent.getActivity(context, NON_ZERO_REQUEST_CODE, intent, 
    PendingIntent.FLAG_UPDATE_CURRENT);
}

FLAG_ACTIVITY_SINGLE_TOP은 기존 활동이 작업 스택의 최상위에있는 경우 기존 활동을 엽니 다. FLAG_ACTIVITY_CLEAR_TOP은 상단이 아니라 스택 내부에있는 경우 대상 활동 위에서 모든 활동을 제거하고 표시합니다. 작업이 작업 스택에 없으면 새 작업이 생성됩니다. PendingIntent.getActivity ()의 두 번째 매개 변수, 즉 requestCode는 0이 아닌 값을 가져야합니다 (내 스 니펫에서 NON_ZERO_REQUEST_CODE라고도 함). 그렇지 않으면 해당 의도 플래그가 작동하지 않습니다. 나는 그것이 왜 그런지 전혀 모른다. FLAG_ACTIVITY_SINGLE_TOP 플래그는 매니페스트의 활동 태그에서 android : launchMode = "singleTop"와 호환됩니다.


나는 그것이 오래되었다는 것을 알고 있지만 위의 어떤 것도 내 응용 프로그램에 적합하지 않았습니다.

Without changing manifests and other configuration, here is the code to bring your app back to front - or opening it when it is closed

Intent notificationIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
notificationIntent.setPackage(null); // The golden row !!!
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

I tried this, and it worked even though the IDE was complaining about the code

Intent notificationIntent = new Intent(THIS_CONTEXT, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    PendingIntent intent = PendingIntent.getActivity(THIS_CONTEXT, 0, notificationIntent, Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(THIS_CONTEXT)
            .setSmallIcon(R.drawable.cast_ic_notification_0)
            .setContentTitle("Title")
            .setContentText("Content")
            .setContentIntent(intent)
            .setPriority(PRIORITY_HIGH) //private static final PRIORITY_HIGH = 5;
            .setAutoCancel(true)
            /*.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS)*/;
    NotificationManager mNotificationManager = (NotificationManager) THIS_CONTEXT.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, mBuilder.build());

Since you say you want to start your activity if it's not started already, maybe you wouldn't mind restarting it. I tested a ton of suggestions and flag combinations for the intent as well, this will always bring the activity you need to the front, though it won't keep any state previously associated with it.

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);

API11+ only.


I had a similar issue after adding notifications as found on the android training site. None of the other answers here worked for me, however this answer did work for me. Summary:

final Intent notificationIntent = new Intent(context, YourActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

참고URL : https://stackoverflow.com/questions/19039189/intent-if-activity-is-running-bring-it-to-front-else-start-a-new-one-from-n

반응형