0
点赞
收藏
分享

微信扫一扫

Android的消息通知--Notification


    可以用Activity和Service来开端消息通知,两者的差别在于一个是在前台触发,一个是后台办事触发。
  要应用消息通知,必必要用到两个类: NotificationManager和Notification ,其他NotificationManager的初始化是用getSystemService办法,并且经由过程notify办法来向android体系发送消息栏通知和显示。

代码如下:


有版本层次  

package com.li.tozhilai;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//android 版本 2 使用的api
public void showNotification(View v){
//获取系统服务
NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
/**
* icon 表示图片的意思
* tickerText 标示文本
* when 是吗时候提示该消息
*/
//notification 是有俩部分组成的 第一部分是手机头部的显示 第二部分是当吧头部下拉时显示内容
Notification notification = new Notification(R.drawable.ic_launcher, "音乐播放器", System.currentTimeMillis());
/**
* context 表示的context
* contentTitle 内容标题
* contentText 内容文本
* contentIntent 点击通知栏上的时候决定要跳转的意图
*/
//PendingIntent.FLAG_ONE_SHOT该参数表示标题栏上值显示一次
Intent intents=new Intent(this,MainActivity.class);
PendingIntent intent = PendingIntent.getActivity(this, 0, intents,PendingIntent.FLAG_ONE_SHOT);
//第二部分是当吧头部下拉时显示内容
notification.setLatestEventInfo(this,
"标题",
"文本内容", intent);
/**
* id :来标示当前的提示
* notification:用来封装了提示的内容
*/

manager.notify(0, notification);//用来提示用户的
}
//点击取消提示框
public void clickCloseShow(View v){
//获取系统服务
NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//manager.cancel(id);该方法指定取消id为及的提示框
manager.cancelAll();//表示取消全部的提示框
}
//android 版本 4 使用的api
public void showNotificationBy4(View v){
//拿到系统服务
NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.icon=R.drawable.ic_launcher;//设置图片
notification.tickerText="标题文本";//标题文本
notification.when=System.currentTimeMillis();//设置显示时间
Intent intent = new Intent(this,MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
notification.setLatestEventInfo(this, "音乐", "正在播放", contentIntent);
manager.notify(1, notification);
}
}


举报

相关推荐

0 条评论