[英]Notification start application else bring activity to front
我的申請中有多項活動。 其中一項活動是啟動活動,這是主要的發射器活動。 它啟動並初始化幾個類,這些類被整個應用程序使用並完成。
然后是主要活動,用戶大部分時間都在這里活動。 如果應用程序關閉時創建通知,則會銷毀這些類,因此應用程序會出錯(nullpointerexception)。
我們需要做的是在應用程序關閉時啟動啟動器活動,否則將主要活動放在前面。
我在這里試過多種解決方案。
這些解決方案都不起作用。 任何幫助表示贊賞。
更新1:
我雖然如果我們通過檢查應用程序是否正在運行來選擇應該通過掛起的意圖獲得哪個意圖。
public boolean isApplicationRunning(Context context) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (RunningTaskInfo task : tasks) {
if (context.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName()))
return true;
}
return false;
}
這解決了我們在多個活動中遇到的問題。 但這會產生另一個問題,如果用戶處於主要活動並收到通知,那么用戶關閉應用程序但不點擊通知。 稍后當用戶點擊通知時,應用程序將再次給出nullpointerexception,因為在創建通知時,應用程序正在運行。
必須有更好的方法來處理這個問題。
沒有人能夠回答我的問題。 所以,我被迫使用一點點臟的解決方案。
所以我們還需要一個類NotificationActivity
。
從后端服務器收到新通知時。 我們將pendingIntent發送到NotificationActivity。
NotificationCompt.Builder = bla bla bla.
Intent intent = new Intent(context, NotificationActivity.class);
intent.setFlags(FLAG_ACTIVITY_CREATE_NEW_TASK);
PendingIntent pIntent = PendingIntent.startIntent(0, intent, 0, someflags);
在NotificationActivity中:
public class NotificationActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstances) {
Intent intent = null;
try {
// Call any method from class which is need by Main activity
someclass.somemethod();
// If we are here then it means app is running.
intent = new Intent(context, MainActivity.class);
// Flag it to bring it to front
intent.setFlags(FLAG_ACTIVITY_BRING_TO_FRONT);
} catch (NullPointerException e ) {
// If we are here then it means that app is closed and
// someclass is garbage collected.
intent = new Intent(context, StartAppActivity.class);
// Flag it to create new task
intent.setFlags(FLAG_ACTIVITY_CREATE_NEW_TASK);
}
// Start intent, and finish this activity
startActivity(intent);
finish();
}
}
這解決了我上面提到的所有問題。 不知道它是否會產生新問題。 如果您使用此方法,請使用低成本的方法。 完成后,此活動將被垃圾收集。 好! 我在最近的將來撒謊。
如果您有多個通知,這會產生問題,但是android允許您將所有通知放入單個pendingIntent中,因此問題永遠不會出現。
我不能提出任何其他問題..如果你可以告訴我或等到它被測試:D
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.