您的位置:首页 > 其它

点开通知栏,回到原界面

2015-07-08 09:01 218 查看
Android点击通知栏信息后返回正在运行的程序,而不是一个新Activity

很多网上关于 通知栏的例子都是打开一个新的Activity,代码也很多。

根据那些代码如下

public void shownotification(String tab)

{

NotificationManager barmanager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

Notification msg2=new Notification(android.R.drawable.stat_notify_chat,"信息",System.currentTimeMillis());

PendingIntent contentIntent =PendingIntent.getActivity(this, 0,new Intent(this,MsgClient.class),PendingIntent.FLAG_ONE_SHOT);

msg2.setLatestEventInfo(this,"服务器端发回信息了","信息:"+tab, contentIntent);

barmanager.notify(NOTIFICATION,msg2);

//Toast.makeText(ReceiveMessage.this, tab,Toast.LENGTH_SHORT).show();

//System.out.println(tab);

}

写出来运行之后,发现结果基本可以实现,但是点击通知栏进入的Activity是一个新创建的Activity,而不是原先正在运行的Activity,这和我的想法是背道而驰的。当你点击返回按键退出这个Activity之后,发现,原先正在运行的Activity终于出现了。明显这样是不符合条理的。

如果要实现点击通知图标返回已经运行的程序,贴出关键的部分代码。

public void shownotification(String msg)

{

NotificationManager barmanager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

Notification notice = new Notification(android.R.drawable.stat_notify_chat,"服务器发来信息了",System.currentTimeMillis());

notice.flags=Notification.FLAG_AUTO_CANCEL;

Intent appIntent = new Intent(Intent.ACTION_MAIN);

//appIntent.setAction(Intent.ACTION_MAIN);

appIntent.addCategory(Intent.CATEGORY_LAUNCHER);

appIntent.setComponent(new ComponentName(this.getPackageName(), this.getPackageName() + "." + this.getLocalClassName()));

appIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);//关键的一步,设置启动模式

PendingIntent contentIntent =PendingIntent.getActivity(this, 0,appIntent,0);

notice.setLatestEventInfo(this,"通知","信息:"+msg, contentIntent);

barmanager.notify(STATUS_BAR_ID,notice);



}

。。。。。。。。。。。。

之前在写好Notification之后,发现按Home回到主界面,再按通知栏的消息(Notification),并没有回到退出之前正在运行的Acticity,后来尝试了挺多方法总是失败。不过我最终还是解决了这个问题,主要是要在代码中加入两行代码作为声名即可。废话不多说,如下:



Intent notificationIntent = new Intent(this.context,this.context.getClass());

/*add the followed two lines to resume the app same with
previous statues*/

notificationIntent.setAction(Intent.ACTION_MAIN);

notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);

/**/

PendingIntent contentIntent = PendingIntent.getActivity(this.context,
0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);


mNotificationManager.notify(NOTIFICATION_SERVICE_ID,notification);

在声明Notification的跳转Intent时,需要给其添加上述红色标出的两行代码,即可使每次按Notification时回到原先正在运行的Activity上面。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: