最近在做一个项目,有用到在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.