3 回答

TA貢獻1833條經驗 獲得超4個贊
您需要的只是一個簡單的活動,什么也不做。這是一個例子:
public class NotificationActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Now finish, which will drop the user in to the activity that was at the top
// of the task stack
finish();
}
}
設置您的通知以開始此活動。確保清單中此活動的任務親和力與應用程序中其他活動的任務親和力相同(默認情況下,如果您未顯式設置android:taskAffinity,則為)。
當用戶選擇此通知時,如果您的應用程序正在運行,則NotificationActivity將在應用程序任務中最頂層活動的頂部啟動,并且該任務將被置于前臺。當NotificationActivity完成時,它將簡單地使用戶返回到應用程序中最頂層的活動(即,當用戶進入后臺時將其停留在的任何位置)。
如果您的應用程序尚未運行,則此方法將無效。但是,您可以通過以下兩種方法解決此問題:
當您的應用程序未運行時,請確保該通知未出現在通知欄中。
在NotificationActivity的onCreate()方法中,檢查您的應用程序是否正在運行,以及是否未運行,請調用startActivity()并啟動您的應用程序。如果這樣做,請確保在啟動應用程序時設置標志Intent.FLAG_ACTIVITY_NEW_TASK,以便該任務的根活動不是NotificationActivity。

TA貢獻1829條經驗 獲得超9個贊
效果很好,謝謝大衛!以下類檢查應用程序是否已在運行,如果尚未運行,則在完成之前啟動它(如David在選項2中所建議的)。
public class NotificationActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// If this activity is the root activity of the task, the app is not running
if (isTaskRoot())
{
// Start the app before finishing
Intent startAppIntent = new Intent(getApplicationContext(), MainActivity.class);
startAppIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startAppIntent);
}
finish();
}
}

TA貢獻1815條經驗 獲得超6個贊
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
毫無疑問,這可行,但是問題是當您將意圖設置為ACTION_MAIN時。這樣,您將無法將任何捆綁軟件設置為該意圖。我的意思是,由于ACTION_MAIN不能包含任何額外的數據,因此不會從目標活動中接收您的原始數據。
取而代之的是,您可以將活動設置為singleTask并正常調用意圖,而無需設置ACTION_MAIN并從目標活動的onNewIntent()方法接收意圖。
但是請注意,如果您調用super.onNewIntent(intent); 然后將創建該活動的第二個實例。只是不要調用超級方法。
- 3 回答
- 0 關注
- 468 瀏覽
添加回答
舉報