什么牛都不吹,直接上需求
聊天的通知栏提醒, 点击跳转 聊天 的 Fragment。
public static void simpleTXTNotify(String title, String content, int type, String huanxin_id) {
//为了版本兼容 选择V7包下的NotificationCompat进行构造
NotificationCompat.Builder builder = new NotificationCompat.Builder(AppApplication.sInstance);
//Ticker是状态栏显示的提示
builder.setTicker(title + ": " + content);
//第一行内容 通常作为通知栏标题
builder.setContentTitle(title);
//第二行内容 通常是通知正文
builder.setContentText(content);
//第三行内容 通常是内容摘要什么的 在低版本机器上不一定显示
// builder.setSubText("这里显示的是通知第三行内容!");
//ContentInfo 在通知的右侧 时间的下面 用来展示一些其他信息
//builder.setContentInfo("2");
//number设计用来显示同种通知的数量和ContentInfo的位置一样,如果设置了ContentInfo则number会被隐藏
builder.setNumber(2);
//可以点击通知栏的删除按钮删除
builder.setAutoCancel(true);
//系统状态栏显示的小图标
builder.setSmallIcon(R.mipmap.ic_launcher);
//下拉显示的大图标
builder.setLargeIcon(BitmapFactory.decodeResource(AppApplication.sInstance.getResources(), R.mipmap.ic_launcher));
Intent intent = new Intent(AppApplication.sInstance, MsgNotifyReceiver.class);
intent.putExtra(MsgTypeConfig.MSG_NOTIFY_HXID, huanxin_id);
// PendingIntent pIntent = PendingIntent.getActivity(AppApplication.sInstance, 1, intent, 0);
PendingIntent pIntent = PendingIntent.getBroadcast(AppApplication.sInstance, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//点击跳转的intent
builder.setContentIntent(pIntent);
//通知默认的声音 震动 呼吸灯
builder.setDefaults(NotificationCompat.DEFAULT_ALL);
Notification notification = builder.build();
manger.notify(type, notification);
}
最重要的代码其实就只有下面几行:
Intent intent = new Intent(AppApplication.sInstance, MsgNotifyReceiver.class);
intent.putExtra(MsgTypeConfig.MSG_NOTIFY_HXID, huanxin_id);
// PendingIntent pIntent = PendingIntent.getActivity(AppApplication.sInstance, 1, intent, 0);
PendingIntent pIntent = PendingIntent.getBroadcast(AppApplication.sInstance, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//点击跳转的intent
builder.setContentIntent(pIntent);
MsgNotifyReceiver 其实就是一个BroadcastReceiver,在点击通知栏之后,直接发出一个通知,并且,在通知的 intent 里面放入了聊天对象的id:
public class MsgNotifyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String huanxin_id = intent.getStringExtra(MsgTypeConfig.MSG_NOTIFY_HXID);
ChatUser chatUser = LitePal.findUser(huanxin_id);
EventBus.getDefault().post(new StartFragmentEvent(MsgFragment.newInstance(chatUser)));
}
}
在接收到通知之后,就可以做你想做的事情了,不仅仅是跳转,比如邪恶的开启各种后台线程….此处和谐。