1. 程式人生 > >Android更新帶進度條的通知欄

Android更新帶進度條的通知欄

text linear archive last sys package 初始 麻煩 httputils

在網上查詢了下。Android版本號更新通知欄帶進度條,醉了,基本都是復制過來。有的代碼不全,連源代碼下載都沒有。有下載也須要積分,還不能用,真黑心啊!!之前自己也寫過自己定義通知欄Notification,想了還是自己寫吧。

由於在通知欄更新,須要訪問網絡下載。就寫了個服務,在服務中實現了下載個更新。

先看MainActivity代碼:

package com.wsj.wsjdemo;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initGlobal();
        checkVersion();
    }
    /**
     * 初始化全局變量
     * 實際工作中這種方法中serverVersion從服務器端獲取。最好在啟動畫面的activity中運行
     */
    public void initGlobal(){
        try{
            Global.localVersion = getPackageManager().getPackageInfo(getPackageName(),0).versionCode; //設置本地版本號號
            Global.serverVersion = 2;//假定服務器版本號為2。本地版本號默認是1
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
    /**
     * 檢查更新版本號
     */
    public void checkVersion(){
     
        if(Global.localVersion < Global.serverVersion){
            //發現新版本號,提示用戶更新
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("軟件升級")
                 .setMessage("發現新版本號,建議馬上更新使用.")
                 .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int which) {
                         //開啟更新服務UpdateService
                         //這裏為了把update更好模塊化,能夠傳一些updateService依賴的值
                         //如布局ID,資源ID,動態獲取的標題,這裏以app_name為例
                         Intent updateIntent =new Intent(MainActivity.this, UpdateService.class);
                         updateIntent.putExtra("app_name",R.string.app_name);
                         updateIntent.putExtra("downurl","http://www.subangloan.com/Contract/App/Android/caijia_unsign_signed.apk");
                         startService(updateIntent);
                     }
                 })
                 .setNegativeButton("取消",new DialogInterface.OnClickListener(){
                     public void onClick(DialogInterface dialog, int which) {
                         dialog.dismiss();
                     }
                 });
            alert.create().show();
        }else{
            //清理工作,略去
            //cheanUpdateFile(),文章後面我會附上代碼
        }
    }
}

activity_main.xml文件:什麽都沒有就一個簡單界面

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>

在Main中的用到的Global.java

package com.wsj.wsjdemo;

public class Global {
	 //版本號信息
    public static int localVersion = 0;
    public static int serverVersion = 0;
    public static String downloadDir = "app/download/";
}

寫的服務實現UpdateService.java

package com.wsj.wsjdemo;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;


public class UpdateService extends Service {
	private static String down_url; // = "http://192.168.1.112:8080/360.apk";
	private static final int DOWN_OK = 1; // 下載完畢
	private static final int DOWN_ERROR = 0;

	private String app_name;

	private NotificationManager notificationManager;
	private Notification notification;

	private Intent updateIntent;
	private PendingIntent pendingIntent;
	private String updateFile;

	private int notification_id = 0;
	long totalSize = 0;// 文件總大小
	/***
	 * 更新UI
	 */
	final Handler handler = new Handler() {
		@SuppressWarnings("deprecation")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_OK:
				// 下載完畢。點擊安裝
				Intent installApkIntent = getFileIntent(new File(updateFile));
				pendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installApkIntent, 0);
				notification.contentIntent = pendingIntent;
				notification.flags |= Notification.FLAG_AUTO_CANCEL;
				notification.setLatestEventInfo(UpdateService.this, app_name, "下載成功,點擊安裝", pendingIntent);
				notificationManager.notify(notification_id, notification);
				stopService(updateIntent);
				break;
			case DOWN_ERROR:
				notification.setLatestEventInfo(UpdateService.this, app_name, "下載失敗", pendingIntent);
				break;
			default:
				stopService(updateIntent);
				break;
			}
		}
	};

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent != null) {
			try {
				app_name = intent.getStringExtra("app_name");
				down_url = intent.getStringExtra("downurl");
				// 創建文件
				File updateFile = FileUtils.getDiskCacheDir(getApplicationContext(), "xxxx.apk");
				if (!updateFile.exists()) {
					try {
						updateFile.createNewFile();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				// 創建通知
				createNotification();
				// 開始下載
				downloadUpdateFile(down_url, updateFile.getAbsolutePath());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}

	/***
	 * 創建通知欄
	 */
	RemoteViews contentView;

	@SuppressWarnings("deprecation")
	public void createNotification() {

		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notification = new Notification();
		notification.icon = R.drawable.ic_launcher;
		// 這個參數是通知提示閃出來的值.
		notification.tickerText = "開始下載";

		// pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);

		// 這裏面的參數是通知欄view顯示的內容
		notification.setLatestEventInfo(this, app_name, "下載:0%", pendingIntent);

		// notificationManager.notify(notification_id, notification);

		/***
		 * 在這裏我們用自定的view來顯示Notification
		 */
		contentView = new RemoteViews(getPackageName(), R.layout.notification_item);
		contentView.setTextViewText(R.id.notificationTitle, "正在下載");
		contentView.setTextViewText(R.id.notificationPercent, "0%");
		contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);

		notification.contentView = contentView;

		updateIntent = new Intent(this, MainActivity.class);
		updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);

		notification.contentIntent = pendingIntent;
		notificationManager.notify(notification_id, notification);
	}

	/***
	 * 下載文件
	 */
	public void downloadUpdateFile(String down_url, String file) throws Exception {
		updateFile = file;
		HttpUtils HttpUtils = new HttpUtils();
		HttpUtils.download(down_url, file, new RequestCallBack<File>() {

			@Override
			public void onSuccess(ResponseInfo<File> responseInfo) {
				// 下載成功
				Message message = handler.obtainMessage();
				message.what = DOWN_OK;
				handler.sendMessage(message);
				installApk(new File(updateFile), UpdateService.this);
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Message message = handler.obtainMessage();
				message.what = DOWN_ERROR;
				handler.sendMessage(message);
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				super.onLoading(total, current, isUploading);
				double x_double = current * 1.0;
				double tempresult = x_double / total;
				DecimalFormat df1 = new DecimalFormat("0.00"); // ##.00%
				// 百分比格式。後面不足2位的用0補齊
				String result = df1.format(tempresult);
				contentView.setTextViewText(R.id.notificationPercent, (int) (Float.parseFloat(result) * 100) + "%");
				contentView.setProgressBar(R.id.notificationProgress, 100, (int) (Float.parseFloat(result) * 100), false);
				notificationManager.notify(notification_id, notification);
			}
		});
	}
	// 下載完畢後打開安裝apk界面
		public static void installApk(File file, Context context) {
			//L.i("msg", "版本號更新獲取sd卡的安裝包的路徑=" + file.getAbsolutePath());
			Intent openFile = getFileIntent(file);
			context.startActivity(openFile);

		}

		public static Intent getFileIntent(File file) {
			Uri uri = Uri.fromFile(file);
			String type = getMIMEType(file);
			Intent intent = new Intent("android.intent.action.VIEW");
			intent.addCategory("android.intent.category.DEFAULT");
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(uri, type);
			return intent;
		}
		public static String getMIMEType(File f) {
			String type = "";
			String fName = f.getName();
			// 取得擴展名
			String end = fName
					.substring(fName.lastIndexOf(".") + 1, fName.length());
			if (end.equals("apk")) {
				type = "application/vnd.android.package-archive";
			} else {
				// /*假設無法直接打開。就跳出軟件列表給用戶選擇 */
				type = "*/*";
			}
			return type;
		}
}

基本上凝視寫的清清楚楚,這當中用到了Xutils開源框架來下載文件。

如過你認為看的麻煩直接點擊下載demo吧。不須要積分.。

。。


Android更新帶進度條的通知欄