主要涉及4个API —— Intent, PendingIntent, Notification,NotificationManager.
其中Intent 用来启动意图
PendingIntent用来延时启动意图,就是说它不会像Intent那样,app启动后立刻执行,而是现在状态栏中存下来,等到特定时间在启动。
Notification 表示 推送信息本体。
NotificationManager 用来操作 Notification 对象的操作。
1、界面:两个按钮
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn_notifi_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发推送"
/>
<Button
android:id="@+id/btn_notify_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="取消推送"
/>
</LinearLayout>
2、代码实现:
public class NotificationActivity extends Activity {
private Button btn_notify_send;
private Button btn_notify_cancel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
init();
}
private void init() {
btn_notify_send = (Button) findViewById(R.id.btn_notifi_send);
btn_notify_cancel = (Button) findViewById(R.id.btn_notify_cancel);
btn_notify_send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(NotificationActivity.this, MainActivity.class);
//参数只需要注意第1个和第3个,其他两个是requestCode 这一类参数
PendingIntent pi =PendingIntent.getActivity(NotificationActivity.this, 0, intent, 0);
Notification notify = new Notification();
notify.icon = R.drawable.ic_launcher;
notify.tickerText = "启动了其他Activity"; //这里是状态栏显示的文字
notify.when = System.currentTimeMillis();
notify.defaults = Notification.DEFAULT_ALL;
//这里是状态栏展开时显示的文字
notify.setLatestEventInfo(NotificationActivity.this, "普通信息", "点击查看", pi);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(1, notify); //这里的1是一个识别码,在cancel推送信息时,这个识别码要一致才能取消
}
});
btn_notify_cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(1);//这里的1 和 manager.notify(1, notify) 中的 “1” 是同一个
}
});
}
}