android通知的使用——Notification

本文介绍了一个Android应用程序中如何通过NotificationManager创建和管理通知。包括如何设置通知的点击跳转行为、图标、标题和内容等属性,并展示了如何使用按钮触发通知显示及取消通知。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


通知使用的时候不用直接实例化,要用到通知管理器获取系统服务 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

public class MainActivity extends Activity {
private Button button;
private Button button2;
private NotificationManager mNotificationManager;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);


button = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);


button.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Notification.Builder mBuilder = new Notification.Builder(
MainActivity.this);
// 创建意图,当点击通知时,跳转到MyActivity
Intent resultIntent = new Intent(MainActivity.this,
MyActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
MainActivity.this, 0, resultIntent, 0);


mBuilder.setContentIntent(pendingIntent);


// 设置通知的属性信息
mBuilder.setSmallIcon(R.drawable.image5);
mBuilder.setContentTitle("通知");
mBuilder.setContentText("Hello WOrld!");
mBuilder.setTicker("有通知来了");


// 创建通知并执行通知
Notification notification = mBuilder.build();
mNotificationManager.notify(0, notification);


}
});


button2.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNotificationManager.cancel(0);//取消通知,0是通知的标志位
}
});
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值