Notification通知栏
是显示在手机状态的消息,代表一种全局效果的通知
快速创建一个Notification的步骤简单可以分为以下四步:
第一步:通过getSystemService()方法得到NotificationManager对象;
第二步:对Notification的一些属性进行设置比如:内容,图标,标题,相应notification的动作进行处理等等;
第三步:通过NotificationManager对象的notify()方法来执行一个notification的快讯;
第四步:通过NotificationManager对象的cancel()方法来取消一个notificatioin的快讯;
示例:
布局:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" > 6 7 <Button 8 android:id="@+id/notification_open" 9 android:layout_width="fill_parent" 10 android:layout_height="wrap_content" 11 android:text="打开通知栏" /> 12 13 <Button 14 android:id="@+id/notification_close" 15 android:layout_width="fill_parent" 16 android:layout_height="wrap_content" 17 android:text="取消通知栏" /> 18 19 </LinearLayout>
JAVA文件:
1 package information; 2 3 4 5 import android.annotation.SuppressLint; 6 import android.app.Activity; 7 import android.app.Notification; 8 import android.app.Notification.Builder; 9 import android.app.NotificationManager; 10 import android.app.PendingIntent; 11 import android.content.Context; 12 import android.content.Intent; 13 import android.os.Bundle; 14 import android.view.View; 15 import android.view.View.OnClickListener; 16 import android.widget.Button; 17 18 import com.example.allcode.R; 19 20 public class Notification_text_one extends Activity implements OnClickListener{ 21 NotificationManager manger; //通知控制类 22 int notification_id; 23 private Button open; 24 private Button close; 25 @Override 26 protected void onCreate(Bundle savedInstanceState) { 27 // TODO Auto-generated method stub 28 super.onCreate(savedInstanceState); 29 setContentView(R.layout.notification); 30 31 open = (Button) findViewById(R.id.notification_open); 32 close = (Button) findViewById(R.id.notification_close); 33 //系统服务 34 manger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 35 36 open.setOnClickListener(this); 37 close.setOnClickListener(this); 38 } 39 @Override 40 public void onClick(View v) { 41 // TODO Auto-generated method stub 42 switch (v.getId()) { 43 case R.id.notification_open: //打开通知栏 44 sendNotification(); 45 46 break; 47 case R.id.notification_close: 48 manger.cancel(notification_id); //取消通知栏 49 50 break; 51 52 default: 53 break; 54 } 55 } 56 57 private void sendNotification(){ 58 Intent intent = new Intent(this,AlertDialog_text.class); 59 60 PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0); 61 Builder builder = new Notification.Builder(this); 62 builder.setSmallIcon(R.drawable.icon_72); //设置通知栏图标 63 builder.setTicker("Hello"); //设置通知栏提示 64 builder.setWhen(System.currentTimeMillis());//设置时间 65 builder.setContentTitle("这是通知栏标题");//通知栏标题 66 builder.setContentText("这里是通知栏内容");//通知栏内容 67 builder.setContentIntent(pi);//设置点击后的意图 68 //效果,需要添加相应的权限 69 builder.setDefaults(Notification.DEFAULT_SOUND);//设置提示声音 70 builder.setDefaults(Notification.DEFAULT_LIGHTS);//设置指示灯 71 builder.setDefaults(Notification.DEFAULT_VIBRATE);//设置震动 72 //builder.setDefaults(Notification.DEFAULT_ALL);//设置全部效果
//权限 <uses-permission android:name="android.permission.VIBRATE" /> 73 //Notification notification = builder.build();//安卓版本4.1及以上 74 Notification notification = builder.getNotification();//安卓版本4.1以下 75 manger.notify(notification_id,notification); 76 } 77 }
PendingIntent.getActivity(this, 0, intent, 0);
参数:
第二个:
id
第四个:
设置flag位
FLAG_AUTO_CANCEL 该通知能被状态栏的清除按钮给清除掉
FLAG_NO_CLEAR 该通知能被状态栏的清除按钮给清除掉
FLAG_ONGOING_EVENT 通知放置在正在运行
FLAG_INSISTENT 是否一直进行,比如音乐一直播放,知道用户响应
1 notification.flags = Notification.FLAG_NO_CLEAR; // 点击清除按钮时就会清除消息通知,但是点击通知栏的通知时不会消失 2 notification.flags = Notification.FLAG_ONGOING_EVENT; // 点击清除按钮不会清除消息通知,可以用来表示在正在运行 3 notification.flags |= Notification.FLAG_AUTO_CANCEL; // 点击清除按钮或点击通知后会自动消失 4 notification.flags |= Notification.FLAG_INSISTENT; // 一直进行,比如音乐一直播放,知道用户响应
效果图:
下面看一个具体应用,异步任务下载网络上的一个图片,将下载进度放到通知栏里,要求下载时,通知栏不能被删除,下载完成时,通知栏可以被删除
1 package com.example.work; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.net.HttpURLConnection; 7 import java.net.MalformedURLException; 8 import java.net.ProtocolException; 9 import java.net.URL; 10 11 import android.app.Activity; 12 import android.app.ProgressDialog; 13 import android.graphics.Bitmap; 14 import android.graphics.BitmapFactory; 15 import android.os.AsyncTask; 16 import android.os.Bundle; 17 import android.util.Log; 18 import android.view.View; 19 import android.view.View.OnClickListener; 20 import android.widget.Button; 21 import android.widget.ImageView; 22 public class MainActivity extends Activity { 23 private Button btn_load; 24 private ImageView image_load; 25 private ProgressDialog dialog; 26 @Override 27 protected void onCreate(Bundle savedInstanceState) { 28 super.onCreate(savedInstanceState); 29 setContentView(R.layout.activity_main); 30 31 btn_load = (Button) findViewById(R.id.btn_submit); 32 image_load = (ImageView) findViewById(R.id.image); 33 34 35 btn_load.setOnClickListener(new OnClickListener() { 36 @Override 37 public void onClick(View v) { 38 // TODO Auto-generated method stub 39 new DownImageAsyncTask(MainActivity.this,image_load).execute("http://images2015.cnblogs.com/blog/493196/201509/493196-20150901203057606-579869820.jpg"); 40 } 41 }); 42 } 43 44 45 46 }
异步任务类:
1 package com.example.work; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.net.HttpURLConnection; 7 import java.net.MalformedURLException; 8 import java.net.ProtocolException; 9 import java.net.URL; 10 11 import android.app.Notification; 12 import android.app.NotificationManager; 13 import android.content.Context; 14 import android.graphics.Bitmap; 15 import android.graphics.BitmapFactory; 16 import android.os.AsyncTask; 17 import android.support.v4.app.NotificationCompat; 18 import android.util.Log; 19 import android.widget.ImageView; 20 21 class DownImageAsyncTask extends AsyncTask<String, Integer, byte[]> 22 { 23 24 private Context context; 25 private ImageView image; 26 public DownImageAsyncTask(Context context ,ImageView image) 27 { 28 this.context = context; 29 this.image = image; 30 } 31 @Override 32 protected byte[] doInBackground(String... params) { 33 // TODO Auto-generated method stub 34 byte b[] = new byte[1024*1024]; 35 36 if(params[0]!=null) 37 { 38 URL url; 39 try { 40 url = new URL(params[0]); 41 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 42 conn.setRequestMethod("GET"); 43 conn.setConnectTimeout(5000); 44 conn.setDoInput(true); 45 46 //记录当前下载量 47 int current_len = 0; 48 if(conn.getResponseCode()==200) 49 { 50 //获取下载文件的总大小 51 InputStream in = conn.getInputStream(); 52 int len=0; 53 //获取总长度 54 long total = conn.getContentLength(); 55 ByteArrayOutputStream out = new ByteArrayOutputStream(); 56 while((len = in.read(b))!=-1) 57 { 58 out.write(b,0,len); 59 current_len+=len; 60 int progress = (int)(current_len/(float)total*100); 61 //发布进度 62 publishProgress(progress); 63 Log.i("-------------------", progress+""); 64 } 65 b = out.toByteArray(); 66 } 67 68 } catch (MalformedURLException e) { 69 // TODO Auto-generated catch block 70 e.printStackTrace(); 71 } catch (ProtocolException e) { 72 // TODO Auto-generated catch block 73 e.printStackTrace(); 74 } catch (IOException e) { 75 // TODO Auto-generated catch block 76 e.printStackTrace(); 77 } 78 79 80 } 81 82 return b; 83 } 84 85 @Override 86 protected void onPostExecute(byte[] result) { 87 // TODO Auto-generated method stub 88 super.onPostExecute(result); 89 //将网络解析数据转换成bitmap图片格式 90 Bitmap bitmap = BitmapFactory.decodeByteArray(result, 0, result.length); 91 //下载完成后 关闭对话框 92 image.setImageBitmap(bitmap); 93 NotificationCompat.Builder builder = new NotificationCompat.Builder(context); 94 95 builder.setContentTitle("下载"); 96 builder.setContentText("下载完成"); 97 builder.setSmallIcon(R.drawable.ic_launcher); 98 // builder.setOngoing(true);//设置不可以被删除 99 100 101 Notification n = builder.build(); 102 103 NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 104 105 manager.notify(188, n); 106 } 107 //在执行doInputBackground方法前主线程自动执行 108 @Override 109 protected void onPreExecute() { 110 // TODO Auto-generated method stub 111 super.onPreExecute(); 112 113 } 114 115 //当使用publishProgress()方法时 自动调用此方法来更新进度 116 @Override 117 protected void onProgressUpdate(Integer... values) { 118 // TODO Auto-generated method stub 119 NotificationCompat.Builder builder = new NotificationCompat.Builder(context); 120 121 builder.setContentTitle("下载"); 122 builder.setContentText("已经下载"+values[0]+"%"); 123 builder.setSmallIcon(R.drawable.ic_launcher); 124 builder.setOngoing(true);//设置不可以被删除 125 //设置通知栏进度条,第一个参数为最大进度,第二个参数为进度,第三个参数为显示进度,为true时不显示进度条填充效果, 126 builder.setProgress(100, values[0], false); 127 128 129 Notification n = builder.build(); 130 131 NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 132 133 manager.notify(188, n); 134 super.onProgressUpdate(values); 135 } 136 }
布局文件
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" 6 android:gravity="center_horizontal" 7 > 8 9 <ImageView 10 android:layout_width="wrap_content" 11 android:layout_height="wrap_content" 12 android:id="@+id/image" 13 android:src="@drawable/ic_launcher" 14 /> 15 16 <Button 17 android:layout_width="wrap_content" 18 android:layout_height="wrap_content" 19 android:id="@+id/btn_submit" 20 android:text="下载" 21 /> 22 23 </LinearLayout>
效果图: