![](/img/trans.png)
[英]How to launch Android app from already opened activity with appium
[英]Android: how to launch activity from notification when task is already running?
我繼承了這個(Xamarin)Android應用程序。 它由幾個活動組成,它還有一個響應GCM消息的BroadcastReceiver
。 每當收到GCM消息時, BroadcastReceiver
在通知區域中發出通知(例如“某些商店或其他商店有促銷活動” )。
通知附加了PendingIntent
,因此無論何時用戶點擊它,都會啟動應用程序的某個活動A.
顯然, 啟動活動的PendingIntent
需要一個Intent.FLAG_ACTIVITY_NEW_TASK
標志,該標志表示:
使用此標志時,如果任務已在您正在啟動的活動上運行,則不會啟動新活動; 相反,當前任務將簡單地以最后一個狀態被帶到屏幕的前面。
這確實是我所看到的行為。
當應用程序未處於活動狀態時(我從未啟動它或按下“返回”按鈕足以結束任務),然后單擊通知,彈出活動A. (好!)
當應用程序位於活動B的前台並且我點擊通知時,沒有任何反應(糟糕!我要求進行活動A)。
問題 :即使任務已在運行,我怎樣才能打開活動A?
這是我生成通知的方式:
public void CreateNotification(Context context, string title, string desc)
{
var notificationManager = GetSystemService(NotificationService) as NotificationManager;
var notification = new Notification(Resource.Drawable.logosmallblue, title);
notification.Flags = NotificationFlags.AutoCancel;
notification.Sound = RingtoneManager.GetDefaultUri (RingtoneType.Notification);
notification.Vibrate = new long[]{500,1500,500};
var perPlaceUniqueId = desc.GetHashCode();
// workaround for Kitkat bug (https://code.google.com/p/android/issues/detail?id=61850)
GetNotificationPendingIntent(context, perPlaceUniqueId).Cancel();
notification.SetLatestEventInfo(context, title, desc, GetNotificationPendingIntent(context, perPlaceUniqueId));
notificationManager.Notify(perPlaceUniqueId, notification);
}
private PendingIntent GetNotificationPendingIntent(Context context, int requestCode)
{
var uiIntent = new Intent(context, typeof(MainView));
uiIntent.PutExtra(MainView.RECOMMENDED_TAG, true);
return PendingIntent.GetActivity(context, requestCode, uiIntent, PendingIntentFlags.UpdateCurrent);
}
謝謝!
在您的PendingIntent
您沒有使用您要詢問的旗幟。 這段代碼:
private PendingIntent GetNotificationPendingIntent(Context context, int requestCode)
{
var uiIntent = new Intent(context, typeof(MainView));
uiIntent.PutExtra(MainView.RECOMMENDED_TAG, true);
return PendingIntent.GetActivity(context, requestCode, uiIntent, PendingIntentFlags.UpdateCurrent);
}
此外,您可能需要添加Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
。 您還可以添加Intent.FLAG_ACTIVITY_CLEAR_TOP
。 像這樣的東西:
private PendingIntent GetNotificationPendingIntent(Context context, int requestCode)
{
var uiIntent = new Intent(context, typeof(MainView));
uiIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
uiIntent.PutExtra(MainView.RECOMMENDED_TAG, true);
return PendingIntent.GetActivity(context, requestCode, uiIntent, PendingIntentFlags.UpdateCurrent);
}
您使用哪些標志取決於您在用戶啟動通知后希望“后退”按鈕的工作方式。
文件說:
當用戶通過按Home鍵離開任務時,當前活動將停止,其任務將進入后台。 系統保留任務中每個活動的狀態。 如果用戶稍后通過選擇開始任務的啟動器圖標來恢復任務,則任務將到達前台並在堆棧頂部恢復活動。
由此:
http://developer.android.com/guide/components/tasks-and-back-stack.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.