通知是Android的一个比较有特色的功能,当应用程序不在前台运行时,向用户发出的一些提示信息,信息由通知图标、通知标题及下拉可视详细内容组成。Notification用法比较灵活,可以在Activity里创建,可以在广播接收器里创建,也可以在服务里创建。通知在Activity和广播接收器里应用较多,但是创建的方法基本一致。下面是Notification的创建步骤。通知的创建方法
一、获得一个NotificationManager
Class to notify the user of events that happen. This is how you tell the user that something has happened in the background.
Notifications can take different forms:
getSystemService(Class)
.
Notification参考文档
由Context的getSystemService()得到。实例代码: NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)
二、创建一个NotificationCompat.Builder对象
Notification参考文档
A class that represents how a persistent notification is to be presented to the user using the NotificationManager
.
The Notification.Builder
has been added to make it easier to construct Notifications.
三、调用
public class MainActivity extends Activity implements OnClickListener {
//private Button sendNotice;
//public static final int NOTIFICATION_ID = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendNotice = (Button) findViewById(R.id.send_notice);
sendNotice.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.send_notice:
//一、得到一个NotificationManager,获取系统的NOTIFICATION_SERVICE服务
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//二、得到一个NotificationCompat.Builder,并运用其方法完成图标、标题、内容的设置
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)//小通知图标
.setSubText("Tap to view documentation about notifications.")//简化的通知内容或提示
.setTicker("leeyevi")//通知栏的标签
.setContentTitle("My notification")//下拉通知看到标题
.setContentText("Hello World!");//通知内容
//三、Define the Notification's Action
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//四、Set the Notification's Click Behavior
mBuilder.setContentIntent(resultPendingIntent);
manager.notify(1, mBuilder.build());
}
}
}
public class NotificationActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_layout);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//取消通知
manager.cancel(1);
}
}