使用Notication在状态栏上显示通知

1、布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button1"
        android:text="显示通知"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button2"
        android:text="删除通知"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

2、在主活动MainActivity.java的onCreate()方法中,调用getSystemService()方法获取系统的NotificationManager服务

//获取通知管理器,用于发送通知
        final NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

3、获取组件

Button button1 = (Button)findViewById(R.id.button1);//获取“显示通知”按钮
        //为“显示通知”按钮添加单击事件监听器
        button1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Notification notify = new Notification();//创建一个Notification对象
				notify.icon = R.drawable.img06; 
				notify.tickerText = "显示的第一个通知";
				notify.when = System.currentTimeMillis();//设置发送时间
				notify.defaults = Notification.DEFAULT_ALL;//设置默认声音、默认震动和默认闪光灯
				notify.setLatestEventInfo(MainActivity.this, "无题", "每天进度一点点", null);//设置事件信息
				notificationManager.notify(1, notify);//通过通知管理器发送通知
				//添加第二个通知
				Notification notify1 = new Notification(R.drawable.img07,"显示第二个通知",System.currentTimeMillis());
				notify1.flags|=Notification.FLAG_AUTO_CANCEL;//打开应用程序后图标消失
				Intent intent = new Intent(MainActivity.this,ContentActivity.class);
				PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
				notify1.setLatestEventInfo(MainActivity.this, "通知", "查看详细内容", pendingIntent);//设置事件信息
				notificationManager.notify(2, notify1);//通过通知管理器发送通知
			}
		});
4、添加权限

<uses-permission android:name="android.permission.FLASHLIGHT"/>
    <!-- 添加操作振动器的权限 -->
    <uses-permission android:name="android.permission.VIBRATE"/>

5、声明另外一个活动ContentActivity

<activity android:name=".ContentActivity"
            android:label="详细内容"
            android:theme="@android:style/Theme.Dialog"></activity>

6、获取“删除通知按钮”

Button button2 = (Button)findViewById(R.id.button2);//获取“删除按钮”
        button2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				notificationManager.cancel(1);//清楚id号为1的通知
				notificationManager.cancelAll();//清除全部通知
			}
		});



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值