安卓 Notification的使用

主要涉及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” 是同一个
 
				
			}
		});
		
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值