android中通知栏的使用

本实例示范了如何通过NotificationManager来发送和取消notification,界面很简单,只是包括了2个普通按钮,分别用于发送和取消Notification,代码如下:

 

package com.example.notifition;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
   private static final int NOTIFICATION_ID = 123;
private NotificationManager nm;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Button btnSend = (Button) findViewById(R.id.btn_send);
		Button btnCancel = (Button) findViewById(R.id.btn_cancel);
		btnSend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				send();
			}
		});
		btnCancel.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				remove();
			}
			
		});
	}
	//发送
	@SuppressLint("NewApi")
	public void send (){
		//创建一个启动其它activity的Intent
		Intent intent = new Intent(MainActivity.this, OtherActivity.class);
		PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
		Notification notification = new Notification.Builder(MainActivity.this)
		              .setAutoCancel(true)//设置打开该通知,该通知自动消失
		              .setTicker("有新消息")//设置显示状态栏的通知提示信息
		              .setSmallIcon(R.drawable.ic_launcher)//设置通知的图标
		              .setContentTitle("有一条新通知")//设置通知的标题
		              .setContentText("恭喜您,您中了现金500w")//设置通知的内容
		              .setDefaults(Notification.DEFAULT_SOUND |Notification.DEFAULT_LIGHTS)//设置系统默认的声音
		              .setWhen(System.currentTimeMillis())//设置通知的时间
		              .setContentIntent(pi).build()//设置intent
		              ;
		nm.notify(NOTIFICATION_ID,notification);//发送通知
	}
	//取消通知
	public void remove(){
		nm.cancel(NOTIFICATION_ID);//取消通知栏,调用该方法后,通知栏就会消失
         //还可以使用setSounds来设置声音
	}
}

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值