您的位置:首页 > 移动开发 > Android开发

Android Notification的基本应用 (8.1)

2016-05-22 21:39 375 查看
效果:点击按钮,然后发送一条通知,点击通知,程序打开Mainactivity

思路:

1
获取通知管理器NotificationManager

2
设置PendingIntent(点击通知之后的处理,例如打开应用)

3.设置通知的具体显示内容等

4.NotificationManager发送通知
代码如下:

public class NotificationActvity extends Activity implements View.OnClickListener{
private Button sendNotification;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
sendNotification=(Button)findViewById(R.id.send_notification);
sendNotification.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.send_notification:
//获取通知管理
NotificationManager notificationManager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
// 获得PendingIntent 延迟执行的Intent
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

//设置通知到来时的振动时间 此数组依次是静音时长,振动时长,此处是振动两次,中间间隔1秒
// 要在声明文件中声明振动的权限 <uses-permission android:name="android.permission.VIBRATE"/>
long [] vibrates = {0,1000,1000,1000};
// 创建通知对象 notification. setLatestEventInfo() 这个方式是API level11以下的方式,
// API level16 以上已经淘汰了这种方式,改用一下的方式
Notification notification = new Notification.Builder(this)
.setAutoCancel(true)
.setContentTitle("您有一条新消息")
.setContentText("今天深圳气温是24-28度")
.setContentIntent(pendingIntent)//设置点击通知之后启动的意图,此处的意图是跳转到MainActivity界面
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)//点击通知之后,通知取消
.setVibrate(vibrates)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。
// 通过通知管理器来发起通知。如果id不同,则每click,在statu那里增加一个提示
notificationManager.notify(1, notification);

break;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: