我已经实施了一个下载管理器,它会在导航栏上显示完成通知,当用户触摸通知时,它会自动显示我的主要活动。
现在的问题是,当我按下主要活动上的后退按钮时,它会返回到我不希望发生的上一个活动。
我尝试过的CODES是:
主要类别:
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
和此:
@Override
public void onBackPressed() {
super.onBackPressed();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
这是我的下载接收器代码:
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent i) {
if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(i.getAction()))
startActivity(new Intent(getApplicationContext(),MainActivity.class));
else if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(i.getAction())) {
Toast.makeText(ctxt,"Done!",Toast.LENGTH_SHORT).show();
Log.i("download status: ", "Download Completed!");
MyNotificationManager.ShowNotification((Activity) ctxt, MainActivity.GetTheActivity(), R.drawable.ic_launcher, "package " + downloadedFileName),
"package" + downloadedFileName + " is downloaded!"), MyNotificationManager.SoundsType.System);
Log.i("download status: ", "Notification shown!");
DoBackgroundDatabaseOperations proceedDownload = new DoBackgroundDatabaseOperations();
proceedDownload.execute();// Sending the package
}
}
};
这是我的MyNotificationManager类,它具有以下显示通知的方法:
public static enum SoundsType
{
System,
My
}
public SoundsType SoundType;
static Uri soundUri;
public static void ShowNotification(Activity curActivity,Activity targetActivity,int icon,String title,String decs,SoundsType sound)
{
if (sound == SoundsType.System)
soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
else if (sound == SoundsType.My)
soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent notificationIntent = new Intent(curActivity, targetActivity.getClass());
PendingIntent contentIntent = PendingIntent.getActivity(curActivity, 0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(curActivity)
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(decs)
.setSound(soundUri)
.setAutoCancel(true)
.setContentIntent(contentIntent);
NotificationManager manager = (NotificationManager) curActivity.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
现在我该怎么做才能正确处理后退按钮,以便它可以运行到之前的应用程序,或者如果用户从那里启动我的应用程序,则可以进入主屏幕?
我知道这不仅仅是一个问题,而是一个代码问题,但我想这是其他许多问题......
答案 0 :(得分:0)
创建通知时,需要在“Intent:
”上设置以下标志 Intent notificationIntent = new Intent(curActivity, targetActivity.getClass());
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
如果您的应用程序尚未运行,则会启动目标活动。如果您的应用程序已在运行并且您的目标活动仍处于活动状态(即:未完成),那么这将清除任务中位于目标活动之上的所有活动,并启动目标活动的新实例。
根据你的描述,这听起来像你想要的。