簡體   English   中英

如何通過從應用程序通知中導航來重新創建活動?

[英]How to recreate activity by navigating from app notification?

我最近為我的應用程序實施了通知。 我一直在測試的是應用程序應如何工作的行為。 我想這將是這樣的:

收到通知后,開放Comments.class通過意向- > MainActivity.class - >點擊返回(退出應用程序,選擇Android設備的主屏幕) - >通過任務管理器重新打開應用程序- >回到Comments.class

前幾個步驟可以正常工作,但是當我從任務管理器打開備份應用程序時,我注意到它進入了Comments.class ,這與我在其他Android應用程序上進行的測試一樣,似乎是預期的行為。

但是,我的Comments.class某些屬性未設置,我知道是因為未調用我的Comments.classonCreate方法。 有什么理由不會發生這種情況嗎? 這是我的嘗試:

NotificationService.java

Intent resultIntent = new Intent(context, Comments.class);

Intent backIntent = new Intent(context, MainActivity.class);
backIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


//Set a random notification Id for each notification so that if you get multiple, the first does not get replaced.
Random random = new Random();
int notificationId = random.nextInt(9999 - 1000) + 1000;
PendingIntent pendingIntent = PendingIntent.getActivities(context, notificationId, new Intent[] { backIntent, resultIntent}, PendingIntent.FLAG_ONE_SHOT);
//When the notification is actually clicked on
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notificationBuilder.build());

這首先創建通知,並將應用程序通知用戶。 然后Comments.javaonCreate函數被調用當我點擊了預計Notification 然后,我單擊返回,將其導航回MainActivity如下所示:

Comment.java

@Override
public void onBackPressed() {
    super.onBackPressed();
    this.finish();
}

然后,調用並創建MainActivity.java很好。 如果我單擊MainActivity.java ,則執行以下代碼:

這是來自MainActivity.java

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);
}

這將我帶回到設備的主屏幕。 但是,我的應用程序實例仍在后台運行,當我在后台單擊我的應用程序並將其放到前台時,我導航回到Comments.java但是因為未調用Comments.javaonCreate方法,未初始化Activity某些細節。 知道為什么會這樣嗎?

任何幫助,將不勝感激。 謝謝!

將您的初始化放入Comment.java onResume函數中。 這是有關Android Activity Lifecycle的很好的讀物,它可以幫助您正確理解行為。

@Override
public void onResume() {
    // Your initialization
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM