1. 程式人生 > >Android Notification 關閉 取消 震動 關閉取消聲音和 Notification進行下載檔案

Android Notification 關閉 取消 震動 關閉取消聲音和 Notification進行下載檔案

使用builder 進行設定,我用Notification設定無效:

mBuilder.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE);

我單獨設定下面兩句話,沒有效果,我就去掉了,只用上面那句話就解決了;

builder.setVibrate(new long[]{0});

builder.setSound(null);

下面是我的鞋的

import java.lang.reflect.Method;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.widget.RemoteViews;

import com.lidroid.xutils.http.HttpHandler;
import com.redoor.rcs.R;
import com.redoor.rcs.async.xhttp.info.ReqVersionInfo;
import com.redoor.rcs.common.AppContext;
import com.redoor.rcs.utils.MyLog;
import com.redoor.rcs.utils.Utils;

public class NotificationDownUtils {
	private static NotificationManager manager;
	private Builder mBuilder;
	private RemoteViews mRemoteview;
	private static NotificationDownUtils instance;
	private static Context context;
	
	public static  NotificationDownUtils get(){
		if (manager==null) {
			synchronized (NotificationManager.class) {
				if (manager==null) {
					context= AppContext.getContext();
					manager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
					instance=new NotificationDownUtils();
				}	
			}
		}
		return instance;
	}

	private PendingIntent getPendingIntent(ReqVersionInfo gInfo) {
		Intent i=new Intent();
		if (!Utils.isNullOrEmpty(gInfo.getIntentWhichClassName())) {
			i.setClassName(context, gInfo.getIntentWhichClassName());
		}
		return PendingIntent.getActivity(context, gInfo.getId(), i, PendingIntent.FLAG_UPDATE_CURRENT);//requestcode  相同則被覆蓋掉,應該是不行同的
	}
	
	private NotificationCompat.Builder createInviteNBuilder(ReqVersionInfo gInfo){
		Builder builder =new Builder(context);
		builder.setWhen(System.currentTimeMillis())
				.setContentIntent(getPendingIntent(gInfo))//此處是用廣播處理了,這裡就不用了
				.setSmallIcon(R.drawable.ic_launcher)
				.setTicker("檢測有新版本")
				.setDefaults(Notification.FLAG_SHOW_LIGHTS)
				.setPriority(Notification.PRIORITY_DEFAULT)
				.setOngoing(true)//true:必須手動清除程式碼
				.setDefaults(Notification.DEFAULT_ALL);
		return builder;
	}


	public void showDownloadNotification(ReqVersionInfo gInfo){
		if (mBuilder==null) {
			mBuilder=createInviteNBuilder(gInfo);
		}
		if (mRemoteview==null) {
			mRemoteview=new RemoteViews(context.getPackageName(), R.layout.notification_download);
		}
		mRemoteview.setImageViewResource(R.id.iv_image, R.drawable.ic_launcher);
		mRemoteview.setTextViewText(R.id.title, gInfo.getName());
		mRemoteview.setTextViewText(R.id.progress_str,gInfo.getProgressStr());
		mRemoteview.setProgressBar(R.id.roundProgressBar, 100, gInfo.getProgress(), false);
		MyLog.e("NotificationDownUtils.java", "NotificationDownUtils gInfo = "+gInfo);
		String stateRes="開始";
		String intentfilter=null;
		if (gInfo.getLoading_state()==HttpHandler.State.CANCELLED.value()) {
			stateRes="取消";//已取消
			intentfilter=NotificationBroadcast.NOTIFICATION_VERSION_CANCLE;
		}else if (gInfo.getLoading_state()==HttpHandler.State.FAILURE.value()){
			stateRes="失敗";
			intentfilter=NotificationBroadcast.NOTIFICATION_VERSION_DOWNLOAD;
		}else if (gInfo.getLoading_state()==HttpHandler.State.LOADING.value()){
			stateRes="下載中";
			intentfilter=NotificationBroadcast.NOTIFICATION_VERSION_CANCLE;
		}else if (gInfo.getLoading_state()==HttpHandler.State.STARTED.value()){
			stateRes="開始";
			intentfilter=NotificationBroadcast.NOTIFICATION_VERSION_DOWNLOAD;
		}else if (gInfo.getLoading_state()==HttpHandler.State.SUCCESS.value()){
			stateRes="安裝";//下載成功後就是安裝
			intentfilter=NotificationBroadcast.NOTIFICATION_VERSION_INSTALL;
		}else if (gInfo.getLoading_state()==HttpHandler.State.WAITING.value()){
			stateRes="等待";
//			intentfilter=NotificationBroadcast.NOTIFICATION_VERSION_DOWNLOAD;
		}
		mRemoteview.setTextViewText(R.id.tv_send_state, stateRes);
		mRemoteview.setOnClickPendingIntent(R.id.tv_send_state,getAnswerPI(gInfo,intentfilter));
		
		
//		if (false) {
//            mBuilder.build().sound = null;//取消鈴聲
//            mBuilder.build().vibrate = null;//取消震動
//        } else {
//            mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);//恢復系統預設設定
//        }
		mBuilder.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE);//取消震動,鈴聲其他都不好使
		//mBuilder.setVibrate(new long[]{0l});
		//mBuilder.setSound(null);
		Notification notification=mBuilder.build();
		notification.contentView=mRemoteview;
		
		//設定在通知發出的時候的音訊  
	    notification.ledARGB = Color.BLUE; 
	    notification.ledOnMS = 1000; 
		notification.ledOffMS = 1000; 
		notification.flags |= Notification.FLAG_SHOW_LIGHTS;

//		notification.sound = null;//取消鈴聲,設定null無濟於事
//		notification.vibrate = new long[]{10000l,1l,10000l,1l};//取消震動,設定null無濟於事
		
		
//	    AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
//         int ringerMode = am.getRingerMode();
//		 long v1[] = {0, 0, 0, 0}; 
//        switch (ringerMode) {//0位靜音,1為震動,2為響鈴
//		case AudioManager.RINGER_MODE_NORMAL:
//			notification.defaults |= Notification.DEFAULT_SOUND;// 系統預設聲音
//			notification.vibrate = v1;
//			break;
//		case AudioManager.RINGER_MODE_VIBRATE://只震動時
//			// 震動頻率	
//			//第一個,0表示手機靜止的時長,			第二個,1000表示手機震動的時長   
//			//第三個,1000表示手機震動後靜默的時長,第四個,1000表示手機震動的時長
//			//此處表示手機先震動1秒,然後靜止1秒,然後再震動1秒 
//			notification.vibrate = v1;
//			break;
//		case AudioManager.RINGER_MODE_SILENT://靜音
//			notification.vibrate = v1;
////			notification.defaults |= Notification.DEFAULT_SOUND;// 系統預設聲音
//			
//			break;
//		default:
//			break;
//		}
		
//		notification.defaults = Notification.DEFAULT_ALL; 
		notification.tickerText="下載中...";
		notification.icon=R.drawable.ic_launcher;
		
		notification.when=System.currentTimeMillis();
		
		
		manager.notify("RCS",gInfo.getId(), notification);

		MyLog.e(" NotificationGrouputils  ", "  showInviteNotification  gInfo.id = "+gInfo.getId() );
	}
	
	public void cancelByid(int id){
		manager.cancel("RCS", id);
	}
	
	public void update(ReqVersionInfo gInfo){
		showDownloadNotification(gInfo);
	}
	
	/** 
	 * 獲取延遲意圖(PedingIntent),進行處理點選事件
	 */
	private PendingIntent getAnswerPI(ReqVersionInfo gInfo,String intentfilter){
		Intent iRJ=new Intent();
		iRJ.setAction(intentfilter);
		iRJ.putExtra(NotificationBroadcast.NOTIFICATION_DATA, gInfo);
		
		PendingIntent iReject=PendingIntent.getBroadcast
				(context, gInfo.getId(), iRJ, PendingIntent.FLAG_UPDATE_CURRENT);//requestcode  相同則被覆蓋掉,應該是不行同的
		return iReject;
	}
	
//	
	/**  收起通知欄
     * <br><b>需要新增許可權:<br>< uses-permission android:name="android.permission.EXPAND_STATUS_BAR" /></b>
     */
    public static void collapseStatusBar(Context context) {
        try {
            Object statusBarManager = context.getSystemService("statusbar");
            Method collapse;

            if (Build.VERSION.SDK_INT <= 16) {
                collapse = statusBarManager.getClass().getMethod("collapse");
            } else {
                collapse = statusBarManager.getClass().getMethod("collapsePanels");
            }
            collapse.invoke(statusBarManager);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }
	
	
	

}

//我的廣播處理Notification下載事件:
import java.io.File;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.view.View;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.redoor.rcs.async.xhttp.ReqVersion;
import com.redoor.rcs.async.xhttp.info.ReqVersionInfo;
import com.redoor.rcs.common.AppContext;
import com.redoor.rcs.common.util.CommonUtil;
import com.redoor.rcs.common.util.GroupMessageUtil;
import com.redoor.rcs.common.util.IOnPressCallBack;
import com.redoor.rcs.utils.FileOpenUtils2;
import com.redoor.rcs.utils.FileUtils;
import com.redoor.rcs.utils.MyLog;
import com.redoor.rcs.utils.Utils;
import com.zte.sdk.util.SdkConstants;

/**
 * @version 1.0
 *
 * @author DongXiang
 * 
 * @action 在修改廣播頻路的時候,別忘記修改清單檔案裡面的廣播
 * 
 * @time 2017年7月21日下午2:42:30
 * 
 */
public class NotificationBroadcast extends BroadcastReceiver{
	private HttpHandler<File> httpHandler=null;
	ReqVersionInfo rvInfo=null;
	
	public static final String NOTIFICATION_DATA="NOTIFICATION_DATA";
	/** 群聊邀請:接收*/
	public static final String NOTIFICATION_INVITE_GROUP_ACCEPT="NOTIFICATION_INVITE_GROUP_ACCEPT";
	/** 群聊邀請:拒絕*/
	public static final String NOTIFICATION_INVITE_GROUP_REJECT="NOTIFICATION_INVITE_GROUP_REJECT";
//	版本檢測廣播
	public static final String NOTIFICATION_VERSION_UPDATE="NOTIFICATION_VERSION_UPDATE";
	/** 下載-包括繼續下載 */
	public static final String NOTIFICATION_VERSION_DOWNLOAD="NOTIFICATION_VERSION_DOWNLOAD";
	/** 取消-也就是等待 */
	public static final String NOTIFICATION_VERSION_CANCLE="NOTIFICATION_VERSION_CANCLE";
	/** 按裝---按裝*/
	public static final String NOTIFICATION_VERSION_INSTALL="NOTIFICATION_VERSION_INSTALL";
	@Override
	public void onReceive(Context context, Intent intent) {
		String actionFilter=intent.getAction();
		MyLog.e("NotificationBroadcast", "NotificationBroadcast = "+actionFilter);
		GroupInviteInfo gInfo=null;
		switch (actionFilter) {
		case NOTIFICATION_INVITE_GROUP_ACCEPT:
			gInfo=intent.getParcelableExtra(NOTIFICATION_DATA);
			MyLog.e(" NotificationBroadcast ", "  onReceive  gInfo.id = "+gInfo.id );
			GroupMessageUtil.getInstance().accpetGroupChat(gInfo.groupchatid);
			NotificationGrouputils.get().cancelByid(gInfo.id);
			NotificationDownUtils.collapseStatusBar(context);
			break;
		case NOTIFICATION_INVITE_GROUP_REJECT:
			gInfo=intent.getParcelableExtra(NOTIFICATION_DATA);
			GroupMessageUtil.getInstance().rejectGroupChat(gInfo.groupchatid);
			NotificationGrouputils.get().cancelByid(gInfo.id);
			NotificationDownUtils.collapseStatusBar(context);
			break;
		case NOTIFICATION_VERSION_UPDATE:
			rvInfo=intent.getParcelableExtra(NOTIFICATION_DATA);
			String message=dealMsg(rvInfo);
			
			CommonUtil.showCancleOkDialog(context, message,//廣播彈出對話方塊,需要設定TYPE_SYSTEM_ALERT型別,詳見方法內部
					new IOnPressCallBack(), //cancle
					new IOnPressCallBack(){//ok
						@Override
						public void onClick(View v) {
							super.onClick(v);
//							下載開啟服務進行下載:
							String url=rvInfo.getUrl();
							if (Utils.isNullOrEmpty(url)) {
								url="http://android.xzstatic.com/2017/06/7083767c116eab4e2336d97ff18544db.apk";
							}
							String rcsName=Utils.isNullOrEmpty(rvInfo.getName())?"RCS.apk":rvInfo.getName();
							String localPath=SdkConstants.RCS_FULLPATH +File.separator+rcsName ;//	eg:直接寫  + param3;
							MyLog.e("NOtificationBroadcast.java", "NOtificationBroadcast localPath = "+localPath
									+"; url = "+url);
							
							rvInfo.setFileLocalPath(localPath);
							httpHandler=ReqVersion.downLoad(url, localPath, new RequestCallBack<File>() {
								@Override
								public void onStart() {
									MyLog.e("NotificationBroadcast", 
											"NotificationBroadcast"+" downLoad onStart ");
									rvInfo.setLoading_state(HttpHandler.State.STARTED.value());
									rvInfo.setProgress(0);
									rvInfo.setProgressStr("0/0");
									NotificationDownUtils.get().update(rvInfo);
								}
								@Override
								public void onLoading(long total, long current,
										boolean isUploading) {
									rvInfo.setLoading_state(HttpHandler.State.LOADING.value());
									int progress=1;
									if (total<=0) {
										progress=10;
									}else {
										progress=(int) ((current*100)/total);
									}
									rvInfo.setProgress(progress);
									rvInfo.setProgressStr(Utils.getDateSize(current)+"/"+Utils.getDateSize(total));
									NotificationDownUtils.get().update(rvInfo);
									if (isUploading) {
										MyLog.e("NotificationBroadcast", 
												"NotificationBroadcast"+" downLoad onLoading upload: current/total = " 
														+ current + "/" + total+";progress = "+progress);
									} else {
										MyLog.e("NotificationBroadcast", 
												"NotificationBroadcast"+" downLoad onLoading reply: current/total = " 
														+ current + "/" + total+";progress = "+progress);
									}
								}

								@Override
								public void onSuccess(ResponseInfo<File> responseInfo) {
									rvInfo.setLoading_state(HttpHandler.State.SUCCESS.value());
									int progress=100;
									rvInfo.setProgress(progress);
//									rvInfo.setProgressStr("");
									rvInfo.setFileLocalPath(responseInfo.result.getPath());
									NotificationDownUtils.get().update(rvInfo);
									MyLog.e("NotificationBroadcast", 
											"NotificationBroadcast"+" downLoad  onSuccess : responseInfo.result = "
														+responseInfo.result.getPath());
								}

								@Override
								public void onFailure(HttpException error, String msg) {
									rvInfo.setLoading_state(HttpHandler.State.FAILURE.value());
									NotificationDownUtils.get().update(rvInfo);
									MyLog.e("NotificationBroadcast", 
											"NotificationBroadcast"+" downLoad onFailure :  error.getExceptionCode() = "
														+error.getExceptionCode()+";msg = "+msg);
								}
							});
							
						}
					});
			break;
//明天來了處理,三種頻率的資料:暫停,繼續,取消(目前認為暫停就是取消)
		case NOTIFICATION_VERSION_DOWNLOAD:
			MyLog.e("NOtificationBroadcast.java", "NOtificationBroadcast NOTIFICATION_VERSION_DOWNLOAD");
			if (httpHandler!=null) {
				httpHandler.resume();
			}
			break;
		case NOTIFICATION_VERSION_CANCLE:
			MyLog.e("NOtificationBroadcast.java", "NOtificationBroadcast NOTIFICATION_VERSION_CANCLE");
			if (httpHandler!=null) {
				httpHandler.pause();
			}
			break;
		case NOTIFICATION_VERSION_INSTALL:
			MyLog.e("NOtificationBroadcast.java", "NOtificationBroadcast NOTIFICATION_VERSION_INSTALL");
			if (httpHandler!=null) {
				httpHandler=null;
			}
			NotificationDownUtils.collapseStatusBar(context);
			ReqVersionInfo gInfoT=intent.getParcelableExtra(NOTIFICATION_DATA);
			NotificationDownUtils.get().cancelByid(gInfoT.getId());
			File fileT=new File(gInfoT.getFileLocalPath());
			if (fileT.exists()) {
				FileOpenUtils2.getInstance().openFile(fileT, context);
			}
			
			break;
		
		default:
			break;
		}
	}
	
	private String dealMsg(ReqVersionInfo rvInfo2) {
		StringBuilder sb=new StringBuilder();
		if (!Utils.isNullOrEmpty(rvInfo2.getName())) {
			sb.append("版本名字:"+rvInfo2.getName()+"\n");
		}
		if (!Utils.isNullOrEmpty(rvInfo2.getTime())) {
			sb.append("更新時間:"+rvInfo2.getTime()+"\n");
		}
		if (!Utils.isNullOrEmpty(rvInfo2.getSize())) {
			sb.append("版本大小:"+rvInfo2.getSize()+"\n");
		}
		if (!Utils.isNullOrEmpty(rvInfo2.getUrl())) {
			sb.append("下載地址:"+rvInfo2.getUrl()+"\n");
		}
		if (Utils.isNullOrEmpty(sb.toString())) {
			sb.append("檢測有新版本");
		}
		return sb.toString();
	}

	public static final  <T extends Parcelable> void sendBroadcast(Context context,String intentfilter,T dto){
		Intent intent = new Intent();
		intent.setAction(intentfilter);		
		intent.putExtra(NOTIFICATION_DATA, dto);		
		context.sendBroadcast(intent);		
	}
	
	
	
	
	

}


清單檔案註冊靜態廣播以及對應的許可權你設定好:

        <receiver android:name=".chat.NotificationBroadcast" >
            <intent-filter>
                <action android:name="NOTIFICATION_INVITE_GROUP_ACCEPT" />
                <action android:name="NOTIFICATION_INVITE_GROUP_REJECT" />
                
                <action android:name="NOTIFICATION_VERSION_UPDATE" />
                <action android:name="NOTIFICATION_VERSION_DOWNLOAD" />
                <action android:name="NOTIFICATION_VERSION_CANCLE" />
                <action android:name="NOTIFICATION_VERSION_INSTALL" />
            </intent-filter>
        </receiver>

注意清單檔案你自己處理對應的許可權,每個方法都是用了:

彈框:

 /** Show alert Cancle-Ok dialog. 通常確認提示框,傳入context和提示內容**/
    public static void showCancleOkDialog(Context context,  String tipmessage,IOnPressCallBack iCancle,IOnPressCallBack iOk) {
    	AlertDialog alert = new AlertDialog.Builder(context).create();
    	LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	View view = inflater.inflate(R.layout.common_tip_clearcancel_dialog, null);
    	TextView tvTipmessage = (TextView) view.findViewById(R.id.tv_tipmessage);
    	tvTipmessage.setText(tipmessage);
    	tvTipmessage.setGravity(Gravity.LEFT);
    	TextView rlCancel = (TextView) view.findViewById(R.id.tv_cancel_button);
    	rlCancel.setText(R.string.gatedlaunch_version_upgrade_obd);
    	rlCancel.setTextColor(context.getResources().getColor(R.color.color_f75959));
    	TextView rlOk = (TextView) view.findViewById(R.id.tv_ok_button);
    	rlOk.setText(R.string.gatedlaunch_version_upgrade);
    	rlOk.setTextColor(context.getResources().getColor(R.color.skin_common_theme_text_default_22bdf6));

    	alert.setView(view);
    	alert.setCancelable(true);
    	alert.setCanceledOnTouchOutside(true);
    	iCancle.setAlert(alert);
    	iOk.setAlert(alert);
    	Window window = alert.getWindow();
    	
//    	window.setContentView(R.layout.common_tip_clearcancel_dialog);
//    	TextView tvTipmessage = (TextView) window.findViewById(R.id.tv_tipmessage);
//    	tvTipmessage.setText(tipmessage);
//    	TextView rlCancel = (TextView) window.findViewById(R.id.tv_cancel_button);
//    	TextView rlOk = (TextView) window.findViewById(R.id.tv_ok_button);
    	
    	rlCancel.setOnClickListener(iCancle);
    	rlOk.setOnClickListener(iOk);

    	//廣播裡面彈出對話方塊,同時設定許可權,android.permission.SYSTEM_ALERT_WINDOW
    	window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);//這個要設定在alert.show之前--最接近的位置
    	alert.show();
    }