3 回答

TA貢獻1833條經(jīng)驗 獲得超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();
}
}
設(shè)置您的通知以開始此活動。確保清單中此活動的任務(wù)親和力與應(yīng)用程序中其他活動的任務(wù)親和力相同(默認(rèn)情況下,如果您未顯式設(shè)置android:taskAffinity,則為)。
當(dāng)用戶選擇此通知時,如果您的應(yīng)用程序正在運行,則NotificationActivity將在應(yīng)用程序任務(wù)中最頂層活動的頂部啟動,并且該任務(wù)將被置于前臺。當(dāng)NotificationActivity完成時,它將簡單地使用戶返回到應(yīng)用程序中最頂層的活動(即,當(dāng)用戶進入后臺時將其停留在的任何位置)。
如果您的應(yīng)用程序尚未運行,則此方法將無效。但是,您可以通過以下兩種方法解決此問題:
當(dāng)您的應(yīng)用程序未運行時,請確保該通知未出現(xiàn)在通知欄中。
在NotificationActivity的onCreate()方法中,檢查您的應(yīng)用程序是否正在運行,以及是否未運行,請調(diào)用startActivity()并啟動您的應(yīng)用程序。如果這樣做,請確保在啟動應(yīng)用程序時設(shè)置標(biāo)志Intent.FLAG_ACTIVITY_NEW_TASK,以便該任務(wù)的根活動不是NotificationActivity。

TA貢獻1829條經(jīng)驗 獲得超9個贊
效果很好,謝謝大衛(wèi)!以下類檢查應(yīng)用程序是否已在運行,如果尚未運行,則在完成之前啟動它(如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條經(jīng)驗 獲得超6個贊
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
毫無疑問,這可行,但是問題是當(dāng)您將意圖設(shè)置為ACTION_MAIN時。這樣,您將無法將任何捆綁軟件設(shè)置為該意圖。我的意思是,由于ACTION_MAIN不能包含任何額外的數(shù)據(jù),因此不會從目標(biāo)活動中接收您的原始數(shù)據(jù)。
取而代之的是,您可以將活動設(shè)置為singleTask并正常調(diào)用意圖,而無需設(shè)置ACTION_MAIN并從目標(biāo)活動的onNewIntent()方法接收意圖。
但是請注意,如果您調(diào)用super.onNewIntent(intent); 然后將創(chuàng)建該活動的第二個實例。只是不要調(diào)用超級方法。
- 3 回答
- 0 關(guān)注
- 458 瀏覽
添加回答
舉報