Android 之版本更新

来源:互联网 发布:淘宝店铺违规24分 编辑:程序博客网 时间:2024/05/16 06:41

/**
* 查询手机安装的应用

* @param context
* @return    
*/

  1. public static List<PackageInfo> getAllNotSystemApps(Context context) {
  2. List<PackageInfo> apps = new ArrayList<PackageInfo>();
  3. PackageManager pManager = context.getPackageManager();
  4. List<PackageInfo> paklist = pManager.getInstalledPackages(0);
  5. for (int i = 0; i < paklist.size(); i++) {
  6. PackageInfo pak = (PackageInfo) paklist.get(i);
  7. if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
  8. apps.add(pak);
  9. }
  10. }
  11. return apps;
  12. }


/**
* 判断是否安装过此应用

* @param context  上下文
* @param packageName  应用的包名  清单文件
*          
* @return
*/

  1. public static boolean isHaveApp(Context context, String packageName) {


  2. PackageInfo pa = null;
  3. List<PackageInfo> packages = getAllNotSystemApps(context);


  4. for (int i = 0; i < packages.size(); i++) {
  5. pa = packages.get(i);
  6. String appPackage = pa.packageName;
  7. if (appPackage.equals(packageName.trim())) {
  8. return true;
  9. }
  10. }
  11. return false;
  12. }


/* 卸载
* packageName   应用的包名 清单文件
*  
* */  

  1. public static void uninstallApk(Context context, String packageName) {  
  2.    Uri uri = Uri.parse("package:" + packageName);  
  3.    Intent intent = new Intent(Intent.ACTION_DELETE, uri);  
  4.    context.startActivity(intent);  
  5. }  


 

//得到当前应用的VersionName  VersionCode


  1. private String getVersionName(Context context) {
  2. String versionName = "";
  3. try {
  4. versionName = context.getPackageManager().getPackageInfo(
  5. context.getApplicationInfo().packageName, 0).versionName;
  6. versionCode = context.getPackageManager().getPackageInfo(
  7. context.getApplicationInfo().packageName, 0).versionCode;
  8. } catch (NameNotFoundException e) {
  9. e.printStackTrace();
  10. }
  11. return versionName;
  12. }



操作步骤:

1.首先判断是否安装过应用

2.如果安装过应用,就卸载

3.如果没有安装过,就下载更新


/**
*  判断应用是否安装过
*/
boolean haveApp = AppUtil.isHaveApp(this, "com.ideal.wdm.activity"); 
if (haveApp) {
//如果有就卸载apk
AppUtil.uninstallApk(this, "com.ideal.wdm.activity");
}

getUpate();  //更新下载操作

  1. private void getUpate(){
  2. AlertDialog.Builder builder = new Builder(mContext);

  3. builder.setTitle("升级提示");
  4. //内容模拟写死
  5. builder.setMessage("版本:1.0.1\n大小:6.5M\n1、修改Bug\n2、增加功能");
  6. builder.setNegativeButton("稍后再说", new AlertDialog.OnClickListener() {

  7. @Override
  8. public void onClick(DialogInterface dialog, int which) {
  9. dialog.dismiss();

  10. }
  11. });

  12. builder.setPositiveButton("马上跟新", new AlertDialog.OnClickListener() {

  13. @Override
  14. public void onClick(DialogInterface dialog, int which) {
  15. dialog.dismiss();
  16. Intent intent = new Intent(mContext,DownloadService.class);
  17. //模拟写死
  18. intent.putExtra("url", "Http://cdn.weibaobiao.com/syy2.apk");
  19. startService(intent);
  20. }
  21. });
  22. builder.show();
  23. }

开启服务下载:

  1.   public class DownloadService extends Service{
  2. public static final String DOWNLOAD_PATH = 
  3. Environment.getExternalStorageDirectory().getAbsolutePath()+"/downloads/";
  4. public static final String TAG = "download";
  5. private String url;//下载链接
  6. private Integer length;//文件长度
  7. private String fileName=null;//文件名
  8. private Notification notification;
  9. private RemoteViews contentView;
  10. private NotificationManager notificationManager;
  11. private static final int MSG_INIT = 0;
  12. private static final int URL_ERROR = 1;
  13. private static final int NET_ERROR = 2;
  14. private static final int DOWNLOAD_SUCCESS = 3;
  15. private Handler mHandler = new Handler(){
  16. public void handleMessage(android.os.Message msg) {
  17. switch (msg.what) {
  18. case MSG_INIT:
  19. length =(Integer) msg.obj;
  20. new DownloadThread(url,length).start();
  21. createNotification();
  22. break;
  23. case DOWNLOAD_SUCCESS:
  24. //下载完成
  25. notifyNotification(100, 100);
  26. installApk(DownloadService.this,new File(DOWNLOAD_PATH,fileName));
  27. Toast.makeText(DownloadService.this, "下载完成", 0).show();
  28. break;
  29. case URL_ERROR:
  30. Toast.makeText(DownloadService.this, "下载地址错误", 0).show();
  31. break;
  32. case NET_ERROR:
  33. Toast.makeText(DownloadService.this, "连接失败,请检查网络设置", 0).show();
  34. }
  35. };
  36. };


  37. public IBinder onBind(Intent arg0) {
  38. // TODO Auto-generated method stub
  39. return null;
  40. }
  41. @Override
  42. public int onStartCommand(Intent intent, int flags, int startId) {
  43. if(intent != null){
  44. //接收activity传过来的地址:
  45. url = intent.getStringExtra("url");
  46. if(url != null && !TextUtils.isEmpty(url)){
  47. new InitThread(url).start();
  48. }else{
  49. mHandler.sendEmptyMessage(URL_ERROR);
  50. }
  51. }
  52. return super.onStartCommand(intent, flags, startId);
  53. }
  54. /**
  55. * 初始化子线程
  56. * @author dong
  57. *
  58. */
  59. class InitThread extends Thread{
  60. String url = "";
  61. public InitThread(String url) {
  62. this.url = url;
  63. }
  64. public void run() {
  65. HttpURLConnection conn= null;
  66. RandomAccessFile raf = null;
  67. try {
  68. //连接网络文件
  69. URL url = new URL(this.url);
  70. conn = (HttpURLConnection) url.openConnection();
  71. conn.setConnectTimeout(3000);
  72. conn.setRequestMethod("GET");
  73. int length = -1;
  74. if(conn.getResponseCode() == HttpStatus.SC_OK){
  75. //获得文件长度
  76. length = conn.getContentLength();
  77. }
  78. if(length <= 0){
  79. return;
  80. }
  81. File dir = new File(DOWNLOAD_PATH);
  82. if(!dir.exists()){
  83. dir.mkdir();
  84. }
  85. fileName = this.url.substring(this.url.lastIndexOf("/")+1, this.url.length());
  86. if(fileName==null && TextUtils.isEmpty(fileName) && !fileName.contains(".apk")){
  87. fileName = getPackageName()+".apk";
  88. }
  89. File file = new File(dir, fileName);
  90. raf = new RandomAccessFile(file, "rwd");
  91. //设置文件长度
  92. raf.setLength(length);
  93. mHandler.obtainMessage(MSG_INIT,length).sendToTarget();
  94. } catch (Exception e) {
  95. mHandler.sendEmptyMessage(URL_ERROR);
  96. e.printStackTrace();
  97. } finally{
  98. try {
  99. conn.disconnect();
  100. raf.close();
  101. } catch (Exception e) {
  102. e.printStackTrace();
  103. }
  104. }
  105. }
  106. }
  107. /**
  108. * 下载线程
  109. * @author dong
  110. *
  111. */
  112. class DownloadThread extends Thread{
  113. String url;
  114. int length;
  115. public DownloadThread(String url, int length) {
  116. this.url = url;
  117. this.length = length;
  118. }
  119. @Override
  120. public void run() {
  121. HttpURLConnection conn = null;
  122. RandomAccessFile raf = null;
  123. InputStream input = null;
  124. try {
  125. URL url = new URL(this.url);
  126. conn = (HttpURLConnection) url.openConnection();
  127. conn.setConnectTimeout(3000);
  128. conn.setRequestMethod("GET");
  129. //设置下载位置
  130. int start =0;
  131. conn.setRequestProperty("Range", "bytes="+0+"-"+length);
  132. //设置文件写入位置
  133. File file = new File(DownloadService.DOWNLOAD_PATH,fileName);
  134. raf = new RandomAccessFile(file, "rwd");
  135. raf.seek(start);
  136. long mFinished = 0;
  137. //开始下载
  138. if(conn.getResponseCode() == HttpStatus.SC_PARTIAL_CONTENT){
  139. //LogUtil.i("下载开始了。。。");
  140. //读取数据
  141. input = conn.getInputStream();
  142. byte[] buffer = new byte[1024*4];
  143. int len = -1;
  144. long speed = 0;
  145. long time = System.currentTimeMillis();
  146. while((len = input.read(buffer)) != -1){
  147. //写入文件
  148. raf.write(buffer,0,len);
  149. //把下载进度发送广播给Activity
  150. mFinished += len;
  151. speed += len;
  152. if(System.currentTimeMillis() - time > 1000){
  153. time = System.currentTimeMillis();
  154. notifyNotification(mFinished,length);
  155. Log.i(TAG, "mFinished=="+mFinished);
  156. Log.i(TAG, "length=="+length);
  157. Log.i(TAG, "speed=="+speed);
  158. speed = 0;
  159. }
  160. }
  161. mHandler.sendEmptyMessage(DOWNLOAD_SUCCESS);
  162. Log.i(TAG, "下载完成了。。。");
  163. }else{
  164. Log.i(TAG, "下载出错了。。。");
  165. mHandler.sendEmptyMessage(NET_ERROR);
  166. }
  167. } catch (Exception e) {
  168. e.printStackTrace();
  169. } finally{
  170. try {
  171. if(conn != null){
  172. conn.disconnect();
  173. }
  174. if(raf != null){
  175. raf.close();
  176. }
  177. if(input != null ){
  178. input.close();
  179. }
  180. } catch (IOException e) {
  181. e.printStackTrace();
  182. }
  183. }
  184. }
  185. }
  186. @SuppressWarnings("deprecation")
  187. public void createNotification() {
  188.         notification = new Notification(
  189.                 R.drawable.ic_launcher,//应用的图标
  190.                 "安装包正在下载...",
  191.                 System.currentTimeMillis());
  192.         notification.flags = Notification.FLAG_ONGOING_EVENT;
  193.         //notification.flags = Notification.FLAG_AUTO_CANCEL;
  194.         
  195.         /*** 自定义  Notification 的显示****/
  196.         contentView = new RemoteViews(getPackageName(),R.layout.notification_item);
  197.         contentView.setProgressBar(R.id.progress, 100, 0, false);
  198.         contentView.setTextViewText(R.id.tv_progress, "0%");
  199.         notification.contentView = contentView;


  200.         /*updateIntent = new Intent(this, AboutActivity.class);
  201.        updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
  202.       updateIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  203.       pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
  204.        notification.contentIntent = pendingIntent;*/
  205.         notification.flags = Notification.FLAG_AUTO_CANCEL;
  206.         notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  207.         
  208.         //设置notification的PendingIntent
  209. /*Intent intt = new Intent(this, MainActivity.class);
  210. PendingIntent pi = PendingIntent.getActivity(this,100, intt,Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
  211. notification.contentIntent = pi;*/
  212.         
  213. notificationManager.notify(R.layout.notification_item, notification);
  214.     }
  215. private void notifyNotification(long percent,long length){
  216. contentView.setTextViewText(R.id.tv_progress, (percent*100/length)+"%");
  217.         contentView.setProgressBar(R.id.progress, (int)length,(int)percent, false);
  218.         notification.contentView = contentView;
  219.         notificationManager.notify(R.layout.notification_item, notification);
  220. }
  221. /**
  222.      * 安装apk
  223.      *
  224.      * @param context 上下文
  225.      * @param file    APK文件
  226.      */
  227.     public static void installApk(Context context, File file) {
  228.         Intent intent = new Intent();
  229.         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  230.         intent.setAction(Intent.ACTION_VIEW);
  231.         intent.setDataAndType(Uri.fromFile(file),
  232.                 "application/vnd.android.package-archive");
  233.         context.startActivity(intent);
  234.     }

  235. }


notification_item.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="60dp"
  5.     android:orientation="horizontal">


  6.     <ImageView
  7.         android:layout_width="60dp"
  8.         android:layout_height="60dp"
  9.         android:background="@drawable/ic_launcher"/>

  10.     <LinearLayout
  11.         android:layout_width="match_parent"
  12.         android:layout_height="wrap_content"
  13.         android:orientation="vertical">
  14.         <RelativeLayout
  15.             android:layout_width="fill_parent"
  16.             android:layout_height="wrap_content"
  17.             >
  18.             <TextView
  19.                 android:layout_centerVertical="true"
  20.                 android:padding="5dp"
  21.                 android:layout_width="wrap_content"
  22.                 android:layout_height="wrap_content"
  23.                 android:text="安装包正在下载..."
  24.                 />
  25.             <TextView
  26.                 android:id="@+id/tv_progress"
  27.                 android:layout_alignParentRight="true"
  28.                 android:padding="5dp"
  29.                 android:layout_width="wrap_content"
  30.                 android:layout_height="wrap_content"
  31.                 android:text="0%"
  32.                 />
  33.         </RelativeLayout>


  34.         <ProgressBar
  35.             android:padding="5dp"
  36.             android:id="@+id/progress"
  37.             style="?android:attr/progressBarStyleHorizontal"
  38.             android:layout_width="fill_parent"
  39.             android:layout_height="wrap_content" />
  40.     </LinearLayout>

  41. </LinearLayout>


最后清单文件注册和添加权限:

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

   <service android:name="com.example.updateservice.DownloadService"></service>


0 0
原创粉丝点击