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();//清除全部通知
}
});