HttpUtils 工具类:
package com.example.android_apk_install; import java.io.File; import java.io.FileOutputStream; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import android.os.Environment; public class HttpUtils { public HttpUtils() { } public static String getMessage(String path) { String str=null; HttpClient httpClient=new DefaultHttpClient(); HttpGet httpGet=new HttpGet(path); try { HttpResponse response=httpClient.execute(httpGet); if(response.getStatusLine().getStatusCode()==200) { String jsonStr=EntityUtils.toString(response.getEntity()); JSONObject jsonObject=new JSONObject(jsonStr); str=jsonObject.getString("versionname"); } } catch (Exception e) { // TODO: handle exception }finally{ httpClient.getConnectionManager().shutdown(); } return str; } /** * 得到APK数据,存到 sdcard卡 * @param path * @return 返回路径 */ public static String downLoadAPK(String path) { byte[] data=null; HttpClient httpClient =new DefaultHttpClient(); File file=Environment.getExternalStorageDirectory(); FileOutputStream outputStream=null; HttpGet httpGet=new HttpGet(path); try { HttpResponse response=httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode()==200) { data=EntityUtils.toByteArray(response.getEntity()); if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //名称需处理 outputStream=new FileOutputStream(new File(file, "abc.apk")); outputStream.write(data, 0, data.length); } } } catch (Exception e) { // TODO: handle exception }finally{ if(outputStream != null) { try { outputStream.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } } return file.getAbsolutePath()+"/"+"abc.apk" ; } }
PackageUtils 工具类
package com.example.android_apk_install; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; /** * 版本信息 * @author Administrator * */ public class PackageUtils { private Context context; private PackageManager manager; private PackageInfo info; public PackageUtils(Context context) { this.context = context; init(); } /** * 初始化数据 */ public void init() { manager = context.getPackageManager(); try { info = manager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public int getVersionCode() { return info.versionCode; } /** * * @return */ public String getVersionName() { return info.versionName; } /** * 是否需要升级 * @param oldVersion * @param newVersion * @return */ public boolean isUpgrada(int oldVersion,int newVersion) { boolean flag = false; flag = newVersion > oldVersion ? true : false; return flag; } }
加权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.INTERNET"/>
MainActivity.java代码:
package com.example.android_apk_install; import java.io.File; import java.io.FileOutputStream; import java.util.concurrent.ExecutionException; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.view.Menu; import android.widget.Toast; public class MainActivity extends Activity { PackageUtils utils; private ProgressDialog dialog; private AlertDialog.Builder builder; private String path="http://........................"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); builder=new AlertDialog.Builder(this); builder.setTitle(" 提示"); builder.setMessage("有新的版本,是否现在更新"); builder.setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); builder.setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); utils=new PackageUtils(this); int currVersionCode=utils.getVersionCode(); dialog=new ProgressDialog(this); dialog.setTitle("提示"); dialog.setMessage("Loading..."); //执行异步任务 try { new MyTask().execute(path).get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public class DownLoadAPK extends AsyncTask< String, Void, Void> { @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); dialog.show(); } @Override protected Void doInBackground(String... params) { // TODO Auto-generated method stub String pathStr=HttpUtils.downLoadAPK(params[0]); System.out.println("---->>"+pathStr); if(pathStr != null) { //"/mnt/sdcard//abc.apk" Uri uri=Uri.fromFile(new File(pathStr)); Intent intent=new Intent(Intent.ACTION_VIEW); intent.setDataAndType(uri, "application/vnd.android.package-archive"); startActivity(intent); } return null; } @Override protected void onPostExecute(Void result) { // TODO Auto-generated method stub super.onPostExecute(result); } } /** * 是否提示下载更新 * @author Administrator * */ class MyTask extends AsyncTask<String, Void, String> { @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); dialog.show(); } @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub //调用 return HttpUtils.getMessage(params[0]); } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); dialog.dismiss(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }