Notification使用

此方法僅提供基本使用,在實際使用中還需要注意細節處理,例 服務解綁等。
示例涉及 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>





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章