此方法仅提供基本使用,在实际使用中还需要注意细节处理,例 服务解绑等。
示例涉及 notification基本使用及自定义样式,通知栏按钮不同方法添加事件,通知栏多个按钮添加事件,服务下载通知栏更新提示下载完成自动安装。
废话不多说直接上代码
NotificationActiviy.java
package com.test;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri.Builder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.test.util.NotifiReceiver;
import com.test.util.NotifiService;
import com.test.util.NotifiService.LocalBinder;
/**
* 通知栏
* @author litz
*/
public class NotificationActiviy extends Activity {
private NotificationManager nm;
private Notification notifi;
private Notification notifi2;
private NotificationCompat.Builder nBuilder;
private NotificationCompat.Builder builder2;
private NotifiService notifiService;
private int notifID = 1000212;
private Context mContext;
private String COVER_CLICK_ACTION = "btn";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dmain);
initLocation();
setOnclick();
}
public void initLocation()
{
mContext = this;
nm = (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
MyApplication.getInstance().notificationManager = nm;
MyApplication.getInstance().mContext = this;
//绑定服务
Intent i=new Intent(this,NotifiService.class);
bindService(i, serConn, Context.BIND_AUTO_CREATE);
}
public void setOnclick()
{
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
showNotif();
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v)
{
nm.cancel(notifID);
}
});
findViewById(R.id.down).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
downNitofi();
}
});
}
//通知栏下载安装
public void downNitofi()
{
builder2 = new NotificationCompat.Builder(mContext);
builder2.setTicker("我要下载了");
builder2.setWhen(System.currentTimeMillis());
builder2.setPriority(NotificationCompat.PRIORITY_MAX);
builder2.setSmallIcon(R.drawable.ic_launcher);
builder2.setOngoing(true);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.item_notification);
Intent intent = new Intent(this, this.getClass());
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder2.setContentIntent(pIntent);
notifi2 = builder2.build();
notifi2.contentView = views;
MyApplication.getInstance().notification = notifi2;
// nm.notify(1021, notifi2);
notifiService.download();
}
public void showNotif()
{
nBuilder = new NotificationCompat.Builder(mContext);
nBuilder.setTicker("我发消息了");
// nBuilder.setAutoCancel(true);//设置这个标志当用户单击面板就可以让通知将自动取消
nBuilder.setOngoing(true);//ture,设置他为一个正在进行的通知。滑动不消除
nBuilder.setWhen(System.currentTimeMillis());//通知产生的时间,会在通知信息里显示,一般是系统获取到的时间
nBuilder.setPriority(NotificationCompat.PRIORITY_MAX);//设置该通知优先级
// nBuilder.setContentTitle("我是同志栏");
// nBuilder.setContentText("内容");
nBuilder.setSmallIcon(R.drawable.ic_launcher);//必须填写不然出不出来 //设置通知小ICON
nBuilder.setDefaults(Notification.DEFAULT_ALL);//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合
// Bitmap largeIcon = BitmapFactory.decodeResource(mContext.getResources(),R.drawable.ic_launcher);
// nBuilder.setLargeIcon(largeIcon);//大图标
RemoteViews views = new RemoteViews(getPackageName(), R.layout.d_notification);
notifi = nBuilder.build();
if(android.os.Build.VERSION.SDK_INT < 16)
{
notifi.contentView = views;
}else{
notifi.bigContentView = views;//只对Android4.1+之后的设备才支持
}
//通知栏跳转
//new Intent(this,this.getClass())保证了点击通知栏里的通知可以回到该Activity
//但是,假如该Activity还在后台运行,并没有运行,通知事件响应后,系统会自动结束该Activity,
//然后再重新启动Activity,这不是我们要的。
//解决方法为:在manifest.xml文件中找到该Activity,添加属性android:launchMode="singleTask“。
//这个属性很明显,就是只允许有一个该Activity运行,如果正在运行,则只能切换到当前运行的Activity,
//而不能重新启动Activity。
Intent intent = new Intent(this, this.getClass());
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
nBuilder.setContentIntent(pIntent);
//一般情况
// IntentFilter filter = new IntentFilter();
// filter.addAction(COVER_CLICK_ACTION);
// registerReceiver(onClickReceiver, filter);
// views.setOnClickPendingIntent(R.id.close, getBtn());
Intent intent3 = new Intent(this,NotifiReceiver.class);
intent3.putExtra("action","close");
intent3.setAction("com.test.NotifiReceiver");
PendingIntent pd3 = PendingIntent.getBroadcast(this, 0, intent3,PendingIntent.FLAG_CANCEL_CURRENT);
views.setOnClickPendingIntent(R.id.close, pd3);
//多个按钮情况
Intent intt1 = new Intent(this,NotifiService.class);
intt1.putExtra("action", "btn1");
PendingIntent prepi = PendingIntent.getService(this, 1, intt1, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.button1, prepi);//----设置对应的按钮ID监控
Intent intent2 = new Intent(this,NotifiService.class);
intent2.putExtra("action", "btn2");
PendingIntent prep2 = PendingIntent.getService(this, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.button2, prep2);//----设置对应的按钮ID监控
nm.notify(notifID, notifi);
}
ServiceConnection serConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
notifiService = ((LocalBinder)service).getService();
}
};
BroadcastReceiver onClickReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(COVER_CLICK_ACTION)) {
Toast.makeText(mContext, "btn", 1000).show();
nm.cancelAll();
System.exit(0);
}
}
};
private PendingIntent getBtn()
{
Intent buttonIntent = new Intent(COVER_CLICK_ACTION);
buttonIntent.setAction(COVER_CLICK_ACTION);
PendingIntent pendButtonIntent = PendingIntent.getBroadcast(this, 0, buttonIntent, 0);
return pendButtonIntent;
}
}
MyApplication.java
package com.test;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
public class MyApplication extends Application {
public Context mContext;
public Notification notification;
public NotificationManager notificationManager;
private static MyApplication myApplication;
@Override
public void onCreate() {
super.onCreate();
myApplication=this;
}
public static MyApplication getInstance(){
return myApplication;
}
}
NotifiReceiver.java
package com.test.util;
import com.test.MyApplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class NotifiReceiver extends BroadcastReceiver {
MyApplication myApplication=MyApplication.getInstance();
Context mContext = MyApplication.getInstance().mContext;
public NotifiReceiver() {
super();
// TODO Auto-generated constructor stub
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra("action");
if(action.equals("close"))
{
Toast.makeText(mContext, "close", 1000).show();
myApplication.notificationManager.cancelAll();
}
}
}
NotifiService.java
package com.test.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.test.CActiviy;
import com.test.MyApplication;
import com.test.R;
public class NotifiService extends IntentService {
private String mUri = "xxxxx";//<span style="font-family: Arial, Helvetica, sans-serif;">下载地址</span>
NotificationManager nm = MyApplication.getInstance().notificationManager;
Notification notifi;
Context mContext = MyApplication.getInstance().mContext;
LocalBinder mBinder = new LocalBinder();
public NotifiService() {
super("NotifiService");
}
public NotifiService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
String type = intent.getStringExtra("action");
Log.d("intent", type);
if (type.equals("btn1")) {
Toast.makeText(mContext, "btn1", 1000).show();
nm.cancelAll();
}
if (type.equals("btn2")) {
Toast.makeText(mContext, "btn2", 1000).show();
nm.cancelAll();
}
}
public void download()
{
notifi = MyApplication.getInstance().notification;
new AsyncTask<Void, Integer, Void>() {
@Override
protected Void doInBackground(Void... params) {
downLoadApk();
return null;
}
void downLoadApk(){
File file=null;
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){//如果SD卡存在
file=new File(Environment.getExternalStorageDirectory(), "test.apk");
}else{//internal storage
file=new File(getFilesDir(),"test.apk");
}
try {
URL url=new URL(mUri);
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
int len=httpURLConnection.getContentLength();
InputStream is=httpURLConnection.getInputStream();
OutputStream os=new FileOutputStream(file, false);
byte buffer[]=new byte[1024];
int readSize=0;//每次读取的大小
int totalSize=0;//累计读取的大小
int temProgress=0;//上一次进度
while((readSize=is.read(buffer))!=-1){
os.write(buffer, 0, readSize);
totalSize+=readSize;
int progress=(totalSize*100/len);//实时进度
if(progress!=temProgress){
publishProgress(progress);
temProgress=progress;
}
}
is.close();
os.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onProgressUpdate(Integer... values) {
int p=values[0];
if(p==100){
notifi.tickerText="下载完成,点击安装";
notifi.contentView.setTextViewText(R.id.content_text, "下载完成,点击安装");
notifi.contentView.setProgressBar(R.id.content_progress, 100, p, false);
Intent intent = new Intent(Intent.ACTION_VIEW);
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"test.apk")), "application/vnd.android.package-archive");
}else{
intent.setDataAndType(Uri.fromFile(new File(getFilesDir(),"test.apk")), "application/vnd.android.package-archive");
}
PendingIntent pi=PendingIntent.getActivity(mContext, 0, intent, 0);
notifi.contentIntent=pi;
notifi.flags=Notification.FLAG_AUTO_CANCEL;
notifi.defaults=Notification.DEFAULT_VIBRATE;
NotificationManager nm=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(110, notifi);
}else{
notifi.contentView.setTextViewText(R.id.content_text, "正在下载"+" "+p+"%");
notifi.contentView.setProgressBar(R.id.content_progress, 100, p, false);
NotificationManager nm=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(110, notifi);
}
}
}.execute();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* 自定义绑定Service类,通过这里的getService得到Service,之后就可调用Service这里的方法了
*/
public class LocalBinder extends Binder {
public NotifiService getService() {
Log.d("playerService", "getService");
return NotifiService.this;
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
布局文件
dmain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="显示Notifacation" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="取消" />
<Button
android:id="@+id/down"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下载通知" />
</LinearLayout>
d_notification.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="@+id/content_view_image"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_centerVertical="true"
android:src="@android:color/white" />
<TextView
android:id="@+id/content_view_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@id/content_view_image"
android:layout_centerVertical="true"
android:text="hahahhahah"
android:textColor="@android:color/white" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp"
android:text="Button2" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button2"
android:layout_alignBottom="@+id/button2"
android:layout_toLeftOf="@+id/button2"
android:text="Button1" />
<Button
android:id="@+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/button2"
android:layout_below="@+id/button2"
android:text="关闭" />
</RelativeLayout>
item_notification.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00000000"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="@+id/content_view_image"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@android:color/white" />
<TextView
android:id="@+id/content_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@id/content_view_image"
android:text="0%"
android:textColor="@android:color/white" />
<ProgressBar
android:id="@+id/content_progress"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/content_view_image"
android:layout_marginTop="4dp"
android:max="100" />
</RelativeLayout>
权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<span style="white-space:pre"> </span><service android:name="com.test.util.NotifiService" >
<intent-filter>
<action android:name="com.test.NotifiService"/>
</intent-filter>
</service>
<receiver android:name="com.test.util.NotifiReceiver" >
<intent-filter>
<action android:name="com.test.NotifiReceiver"/>
</intent-filter>
</receiver>