您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)怎么在Android應(yīng)用中實現(xiàn)一個程序更新下載功能,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
創(chuàng)建一個新類,名為UpdateManager,代碼如下:
import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import com.af.mobile.R; import android.app.AlertDialog; import android.app.Dialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; public class UpdateManager {private URL url=null; /* 下載中 */ private static final int DOWNLOAD = 1; /* 下載結(jié)束 */ private static final int DOWNLOAD_FINISH = 2; /* 保存解析的XML信息 */ //HashMap<String, String> mHashMap; /* 下載保存路徑 */ private String mSavePath; /* 記錄進度條數(shù)量 */ private int progress; /* 是否取消更新 */ private boolean cancelUpdate = false; private Context mContext; /* 更新進度條 */ private ProgressBar mProgress; private Dialog mDownloadDialog; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { // 正在下載 case DOWNLOAD: // 設(shè)置進度條位置 mProgress.setProgress(progress); break; case DOWNLOAD_FINISH: // 安裝文件 installApk(); break; default: break; } }; }; public UpdateManager(Context context) { this.mContext = context; } public void checkUpdate() { if (isUpdate()) { showNoticeDialog(); } else { } } /** * 檢查軟件是否有更新版本 * * @return */ private boolean isUpdate() { // 獲取當(dāng)前軟件版本 Double versionCode = getVersionCode(mContext); Double serviceCode = 1.2; // 版本判斷 if (serviceCode > versionCode) { return true; } return false; } // 獲取軟件版本號 private Double getVersionCode(Context context) { Double versionCode = 0.0; try { // 獲取軟件版本號,對應(yīng)AndroidManifest.xml下android:versionCode versionCode = (double) context.getPackageManager().getPackageInfo("com.af.mobile", 0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } return versionCode; } //顯示軟件更新對話框 private void showNoticeDialog() { AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("軟件更新"); String string=download("http://192.168.0.102:9313/daojuserver/uploads/version.xml");//xml的下載地址 builder.setMessage(string); builder.setPositiveButton("更新", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // 顯示下載對話框 showDownloadDialog(); } }); // 稍后更新 builder.setNegativeButton("稍后更新", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog noticeDialog = builder.create(); noticeDialog.show(); } // 顯示軟件下載對話框 private void showDownloadDialog() { // 構(gòu)造軟件下載對話框 AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("djfkjd");//提示信息內(nèi)容 // 給下載對話框增加進度條 final LayoutInflater inflater = LayoutInflater.from(mContext); View v = inflater.inflate(R.layout.softupdate_progress, null); mProgress = (ProgressBar) v.findViewById(R.id.update_progress); builder.setView(v); // 取消更新 builder.setNegativeButton("取消更新", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // 設(shè)置取消狀態(tài) cancelUpdate = true; } }); mDownloadDialog = builder.create(); mDownloadDialog.show(); // 現(xiàn)在文件 downloadApk(); } private void downloadApk() { // 啟動新線程下載軟件 new downloadApkThread().start(); } private class downloadApkThread extends Thread { @Override public void run() { try { // 判斷SD卡是否存在,并且是否具有讀寫權(quán)限 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 獲得存儲卡的路徑 String sdpath = Environment.getExternalStorageDirectory() + "/"; mSavePath = sdpath + "download"; URL url = new URL("http://192.168.0.102:9313/daojuserver/uploads/SpMobile.apk");//apk下載地址地址 // 創(chuàng)建連接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); // 獲取文件大小 int length = conn.getContentLength(); // 創(chuàng)建輸入流 InputStream is = conn.getInputStream(); File file = new File(mSavePath); if (!file.exists()) { file.mkdir(); } File apkFile = new File(mSavePath, "dhfudh"); FileOutputStream fos = new FileOutputStream(apkFile); int count = 0; // 緩存 byte buf[] = new byte[1024]; // 寫入到文件中 do { int numread = is.read(buf); count += numread; // 計算進度條位置 progress = (int) (((float) count / length) * 100); // 更新進度 mHandler.sendEmptyMessage(DOWNLOAD); if (numread <= 0) { mHandler.sendEmptyMessage(DOWNLOAD_FINISH); break; } fos.write(buf, 0, numread); } while (!cancelUpdate); fos.close(); is.close(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 取消下載對話框顯示 mDownloadDialog.dismiss(); } }; private void installApk() { File apkfile = new File(mSavePath, "dhfudh"); if (!apkfile.exists()) { return; } // 通過Intent安裝APK文件 Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); mContext.startActivity(i); } public String download(String urlString) { StringBuffer sbBuffer=new StringBuffer(); String line=null; BufferedReader buffer=null; try { url=new URL(urlString); HttpURLConnection urlConn=(HttpURLConnection) url.openConnection(); buffer=new BufferedReader(new InputStreamReader(urlConn.getInputStream())); while((line=buffer.readLine())!=null) { sbBuffer.append(line); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { try { buffer.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return sbBuffer.toString(); } }
在Android應(yīng)用程序Main界面
if(isOpenNetwork())//判斷是否有網(wǎng)絡(luò) { UpdateManager manager = new UpdateManager(Main.this); // 檢查軟件更新 manager.checkUpdate(); }
判斷移動端是否有網(wǎng)絡(luò)
private boolean isOpenNetwork() { ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connManager.getActiveNetworkInfo(); if (networkInfo != null) { // 2.獲取當(dāng)前網(wǎng)絡(luò)連接的類型信息 int networkType = networkInfo.getType(); if (ConnectivityManager.TYPE_WIFI == networkType) { // 當(dāng)前為wifi網(wǎng)絡(luò) } else if (ConnectivityManager.TYPE_MOBILE == networkType) { // 當(dāng)前為mobile網(wǎng)絡(luò) } return connManager.getActiveNetworkInfo().isAvailable(); } return false; }
上述就是小編為大家分享的怎么在Android應(yīng)用中實現(xiàn)一個程序更新下載功能了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。