在Andrdoid程序中常常會有一個版本更新的功能,它的實現非常簡單,就是講新版本的apk文件上傳到服務器,然後修改服務器中的版本號,這樣當用戶點擊版本更新的時候就可以下載新版本的apk文件了,下面說一下是如何下載並安裝apk文件的:
public class UpdateActivity extends AppCompatActivity { private Button button1; private static String URL_STRING = "";//下載文件的地址 private static int down = 0;//狀態碼 File file; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: button1.setText("點擊安裝"); down = 1; break; case 2: down = 2; button1.setText("打開"); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update); String apk = getIntent().getStringExtra("apk"); String path = "http://59.110.12.225:8080/szcb.admin"; URL_STRING = path + apk; //調用手機中的瀏覽器下載 // Uri uri = Uri.parse(path+apk); // Intent intent = new Intent(Intent.ACTION_VIEW, uri); // startActivity(intent); button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 下載apk if (down == 0) { downFile(URL_STRING); button1.setText("正在下載"); // 安裝APK } else if (down == 1) { installApk(); // 打開apk } else if (down == 2) { openApk(UpdateActivity.this, URL_STRING); } } }); } // 接收到安裝完成apk的廣播 BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { System.out.println("接收到安裝完成apk的廣播"); Message message = handler.obtainMessage(); message.what = 2; handler.sendMessage(message); } }; /** * 後臺在下面一個Apk 下載完成後返回下載好的文件 * * @param httpUrl * @return */ private File downFile(final String httpUrl) { new Thread(new Runnable() { @Override public void run() { try { URL url = new URL(httpUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); FileOutputStream fileOutputStream = null; InputStream inputStream; if (connection.getResponseCode() == 200) { inputStream = connection.getInputStream(); if (inputStream != null) { file = getFile(httpUrl); fileOutputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; int length = 0; while ((length = inputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, length); } fileOutputStream.close(); fileOutputStream.flush(); } inputStream.close(); } //Log.e("Mr.Kang", "run: "+"下載完成"); // 往handler發送一條消息 更改button的text屬性 Message message = handler.obtainMessage(); message.what = 1; handler.sendMessage(message); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); return file; } /** * 安裝APK */ private void installApk() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startActivity(intent); } @Override protected void onStart() { super.onStart(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED); intentFilter.addDataScheme("package"); // 註冊一個廣播 registerReceiver(broadcastReceiver, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); // 解除廣播 unregisterReceiver(broadcastReceiver); } /** * 打開已經安裝好的apk */ private void openApk(Context context, String url) { PackageManager manager = context.getPackageManager(); // 這裏的是你下載好的文件路徑 PackageInfo info = manager.getPackageArchiveInfo(Environment.getExternalStorageDirectory().getAbsolutePath() + getFilePath(url), PackageManager.GET_ACTIVITIES); if (info != null) { Intent intent = manager.getLaunchIntentForPackage(info.applicationInfo.packageName); startActivity(intent); } } /** * 根據傳過來url創建文件 */ private File getFile(String url) { File files = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), getFilePath(url)); return files; } /** * 截取出url後面的apk的文件名 * @param url * @return */ private String getFilePath(String url) { return url.substring(url.lastIndexOf("/"), url.length()); } }