今天研究下手机中各应用中的消息推送是如何实现的 。Notification,也就是显示在手机状态栏的通知,我们今天的关键字。使用
它的基本步骤如下:
一条自定义消息通知的代码如下:
//消息推送
public void sendNotification(View view){
NotificationManager notificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder=new NotificationCompat.Builder(this);
builder.setContentTitle("情人节");
builder.setContentText("你们尽管秀恩爱,明年还是这个人,算我输");
builder.setDefaults(NotificationCompat.DEFAULT_ALL);
builder.setAutoCancel(true);
builder.setSmallIcon(android.R.drawable.ic_media_play);
builder.setContentIntent(PendingIntent.getActivity(this,0x102,new Intent(this, RingActivity.class),0));
Notification notification=builder.build();
notificationManager.notify(0x101,notification);
}
接下来模拟一下手机中的自定义通知栏:
public class NotificationActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);// requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout. activity_main);Notification notification = new Notification();//设置图标,后面的自定义布局的图片会覆盖它,但还是得设置,不然不会显示到通知栏notification. icon = android.R.drawable. ic_media_play;notification. tickerText = "hello C";notification. when = System. currentTimeMillis();notification. flags = Notification. FLAG_AUTO_CANCEL;//传入当前项目的包名,和你通知栏上要显示的自定义布局的IDRemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout. activity_notification);//下面都是设置通知栏布局里面控件的属性remoteViews.setImageViewResource(R.id. imageView1, android.R.drawable. ic_media_play);remoteViews.setTextColor(R.id. textView1, Color. RED);remoteViews.setTextViewText(R.id. textView1, "hello");
// PendingIntent有4种flag.// - FLAG_ONE_SHOT 只执行一次// - FLAG_NO_CREATE 若描述的Intent不存在则返回NULL值// - FLAG_CANCEL_CURRENT 如果描述的PendingIntent已经存在,则在产生新的Intent之前会先取消掉当前的// - FLAG_UPDATE_CURRENT 总是执行,这个flag用的最多PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent( this, MainActivity. class),PendingIntent. FLAG_UPDATE_CURRENT);remoteViews.setOnClickPendingIntent(R.id. textView1, pendingIntent);notification. contentView = remoteViews;notification. contentIntent = pendingIntent;NotificationManager manager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE);NotificationManager manager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE);NotificationManager manager = (NotificationManager) getSystemService(Context. NOTIFICATION_SERVICE);
manager.notify( 1, notification);
}}