我正在開發一個Android應用程序。在我的應用程序中,我在點擊通知時打開活動。通知中的開放活動在Android中的活動生命週期中存在問題
我有兩個活動 - MainActivity和SecondActivity
主要活動可以打開SecondActivity
OnBackPressed上SecondActivity,MainActivity將顯示背上它是打開SecondActivity活動。 OnBackPressed MainActivity,應用程序將退出。這是默認的活動應用程序首先啓動。現在我遇到了問題,因爲我從服務內部打開了SecondActivity。
我這是怎麼打開SecondActivity從服務
private void showTrollPostNotification(String message)
{
notification = new NotificationCompat.Builder(getApplicationContext());
notification.setAutoCancel(true);
notification.setSmallIcon(R.mipmap.ic_launcher);
notification.setWhen(System.currentTimeMillis());
notification.setTicker(message);
notification.setContentTitle(getApplication().getResources().getString(R.string.app_name));
notification.setContentTitle(message);
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0,i,PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager)getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
nm.notify(1,notification.build());
}
的問題是,當我從服務和SecondActivity的OnBackPressed,退出應用程序打開。我想要做的是當我按下SecondActivity內的按鈕時,我總是想打開MainActivity。所以我嘗試的是重寫SecondActivity的onBackPressed。我在onBackPressed中啓動MainActivity。但問題是,當我從通知中打開SecondActivity時,然後按回按鈕,它將打開MainActivity。
但是,當我按回按鈕然後,它打開SecondActivity回來。我能做些什麼來使MainActivity始終在SecondActivity的OnBackPressed中打開,而不會像現在發生的Activity Cycle一樣發生問題。
這是SecondActivity在清單
<activity
android:noHistory="true"
android:label="Post Details"
android:name=".SecondActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
這onBackPressed SecondActivity
@Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
然後重寫onBackPressed打開MainActivity? –
@WaiYanHein是的 –
我將它添加到清單文件中。然後重寫第二個Activity的onBackPressed。不工作。他們繼續打開對方的背部按下。 –