알림 클릭 : 활동이 이미 열려 있습니다
클릭하면 특정 활동을 여는 알림이있는 응용 프로그램이 있습니다. 알림을 클릭하고 활동이 이미 열려 있으면 다시 시작 되지 않고 바로 시작됩니다.
나는 깃발 FLAG_ACTIVITY_BROUGHT_TO_FRONT
이나로 할 수 있다고 생각 FLAG_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에 변수를 저장해야합니까?
감사!
시작하려는 의 launchMode
속성을 로 설정해야 Activity
합니다 singleTop
. 이로 인해 작업 인스턴스 Activity
의 맨 위에 있을 때 새 인스턴스를 시작하지 않고 기존 인스턴스로 들어오는 인 텐트가 전달됩니다 .
이는 매니페스트 android:launchMode="singleTop"
에서 <activity>
요소 에 추가 하여 수행됩니다 . 최신 의도에 액세스하려면 (이 데이터와 함께 전달 된 데이터에 관심이있는 경우)에서 재정의 onNewIntent()
하십시오 Activity
.
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
대신 플래그를 설정하십시오 .
로부터 FLAG_ACTIVITY_CLEAR_TOP에 대한 설명서 (강조 광산) :
설정된 경우 시작중인 활동이 현재 작업에서 이미 실행 중이면 해당 활동의 새 인스턴스를 시작하는 대신 그 위에있는 다른 모든 활동이 닫히고이 의도는 (현재 맨 위) 새로운 의도로서의 오래된 활동.
예를 들어, 활동 A, B, C, D로 구성된 작업을 고려하십시오. D가 활동 B의 구성 요소로 해석되는 Intent와 함께 startActivity ()를 호출하면 C와 D가 완료되고 B는 주어진 Intent를 수신합니다. 스택의 결과는 A, B입니다.
위 예제에서 현재 실행중인 활동 B의 인스턴스는 onNewIntent () 메소드에서 여기에서 시작중인 새 의도를 수신하거나 새 의도로 완료 및 재시작됩니다. 시작 모드를 "다중"(기본값)으로 선언하고 동일한 의도로 FLAG_ACTIVITY_SINGLE_TOP을 설정하지 않은 경우 완료되고 다시 작성됩니다. 다른 모든 시작 모드 또는 FLAG_ACTIVITY_SINGLE_TOP이 설정된 경우이 의도는 현재 인스턴스의 onNewIntent ()로 전달됩니다.
사용 onNewIntent()
알림 클릭에서 새로운 데이터를 처리하고 활동을 새로 고침합니다.
에서 onNewIntent
(새로운 통지에 의해 제공) 새로운 의도에서 새 데이터를 얻을 예를 들어, 그들을 잡을 :
title = intent.getStringExtra("title")
에서 onCreate
이전에 :)
새로운 알림 데이터로 현재 활동을 새로 고칩니다.
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());
코드를 복사하여 기본 런처 활동에 붙여 넣으십시오.
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, new Random().nextInt(), intent, 0);
작동하도록 논리를 추가해야한다고 생각합니다. 어쩌면 이것이 도움이 될 수 있습니다.
예를 들어 APP의 스플래시 화면 (런처 및 MAIN)이 있습니다.
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);
}
}
}
내 FirebaseService에서 다음을 수행했습니다.
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());
}
}
참고 URL : https://stackoverflow.com/questions/12043671/notification-click-activity-already-open
'IT story' 카테고리의 다른 글
Git을 사용하여 로컬과 원격 사이의 변화를 어떻게 찾을 수 있습니까? (0) | 2020.06.12 |
---|---|
파이썬에서 두 생성기를 결합하는 방법? (0) | 2020.06.12 |
Angular 2-this.router.parent.navigate ( '/ about')를 사용하여 다른 경로로 이동하는 방법? (0) | 2020.06.12 |
Visual Studio Code Editor에서 사용되는 글꼴과 글꼴을 변경하는 방법은 무엇입니까? (0) | 2020.06.12 |
내 앱에서 파일 공유를 활성화하는 방법은 무엇입니까? (0) | 2020.06.12 |