Android Notification为消息推送。具体使用方法将通过一个Demo演示。
public class MyNotification extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//以下为界面布局代码。
LinearLayout linearLayout = new LinearLayout(this);
TextView textView = new TextView(this);
Button btShow = new Button(this);
btShow.setText("send message");
Button btHide = new Button(this);
btHide.setText("cancel message");
linearLayout.addView(textView);
linearLayout.addView(btShow);
linearLayout.addView(btHide);
setContentView(linearLayout);
btShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
btHide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancle();
}
});
}
void sendMessage() {
//发送推送消息
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "hello world", System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.defaults = notification.DEFAULT_SOUND | notification.DEFAULT_VIBRATE;
Intent intent = new Intent(getBaseContext(), MyTextView.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "title", "content", pendingIntent);
manager.notify(notificationId, notification);
}
void cancle() {
//清空推送消息
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notificationId);
}
//标识消息的Id
private static final int notificationId = 1;
}
通过这个简单的Demo就可以初步使用Notification了。