Notification 恢复到最后显示的Activity

最近在做一个项目,有用到在service中启动一个Notification.其中代码很简单,如下

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);

这段代码很容易找到.   但是这里有个问题就是 Intent中指明的ExampleActivity.class是一个具体的类(Activity).无论你当时是从哪个Activity离开程序的,

当你点击通知栏时返回的都是到ExampleActivity 这个activity。这当然是不行的,我们当然希望能够返回到当初我们离开程序的那个状态.


修改后的代码如下:

Notification notification = new Notification(R.drawable.icon1, getText(R.string.app_name), System.currentTimeMillis());
Intent notificationIntent = new Intent(CustomerActivityManager.curActivity,CustomerActivityManager.curActivity.getClass());
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.app_name), mainApplication.getUserInfo().getLoginName(), pendingIntent);
startForeground(NOTIFICATION_ID, notification);

需要解释下: 其中CustomerActivityManager 这个类是我自定义的用来管理activivty的类.其中变量curActivity是应用程序最后显示的activity

public class CustomerActivityManager {
	
    private static LinkedList<Activity> activitys = new LinkedList<Activity>();

    public static Activity curActivity;
    
    public static void add(Activity activity)
    {
    	activitys.add(activity);
    }

    public static void remove(Activity activity) {
    	activitys.remove(activity);
    }
    
    public static void close()
    {
        Activity activity;
        while (activitys.size() != 0)
        {
            activity = activitys.poll();
            if (!activity.isFinishing())
            {
            	activity.finish();
            }
        }
    }
}

那如何给curActivity赋值呢?最后显示的肯定要调用onResume方法,所以在事件onResume中增加,如下;
@Override
protected void onResume()
{
    // TODO Auto-generated method stub
    CustomerActivityManager.curActivity = this;
		
    super.onResume();
}

这段代码只要加在你的BaseActivity中即可,BaseActivity是我们经常定义的一个Activity的一个基类,继承了Activity,所有用户的Activity都继承于BaseActivity,在BaseActivity中加入一些

公共的东西很方便的,如果你之前没有这样做,建议你最好改成这样,绝对有好处的.


最后,我的activity的lanuchMode都是singleTask,如果你的不是的话,Intent启动模式一定要设置为singleTask.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值