zoukankan      html  css  js  c++  java
  • Android 下载App

    转载:http://blog.csdn.net/aicpzl/article/details/52993074


    通过DownloadManager来下载APK到本地,下载完成后收到广播再安装APK,可用在软件更新等场合。

    添加权限

    [html] view plain copy
    1. <uses-permission android:name="android.permission.INTERNET"/>  
    2. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

    Activity源码

    [java] view plain copy
    1. package com.example.administrator.downloadtest;  
    2.   
    3. import android.app.Activity;  
    4. import android.app.DownloadManager;  
    5. import android.content.BroadcastReceiver;  
    6. import android.content.Context;  
    7. import android.content.Intent;  
    8. import android.content.IntentFilter;  
    9. import android.net.Uri;  
    10. import android.os.Bundle;  
    11. import android.view.View;  
    12. import android.webkit.MimeTypeMap;  
    13. import android.widget.Button;  
    14.   
    15.   
    16. public class MainActivity extends Activity {  
    17.   
    18.     @Override  
    19.     protected void onCreate(Bundle savedInstanceState) {  
    20.         super.onCreate(savedInstanceState);  
    21.         setContentView(R.layout.activity_main);  
    22.   
    23.         Button btDownload = (Button) findViewById(R.id.bt_download);  
    24.         btDownload.setOnClickListener(new View.OnClickListener() {  
    25.             @Override  
    26.             public void onClick(View v) {  
    27.                 downloadApk();  
    28.             }  
    29.         });  
    30.         /**注册下载完成广播**/  
    31.         registerReceiver(downloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));  
    32.     }  
    33.     /**下载APK**/  
    34.     private void downloadApk() {  
    35.         String apkUrl = "http://192.168.1.1/downloadtest.apk";  
    36.         Uri uri = Uri.parse(apkUrl);  
    37.         DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);  
    38.         DownloadManager.Request request = new DownloadManager.Request(uri);  
    39.         // 设置允许使用的网络类型,这里是移动网络和wifi都可以  
    40.         request.setAllowedNetworkTypes(request.NETWORK_MOBILE| request.NETWORK_WIFI);  
    41.         //设置是否允许漫游  
    42.         request.setAllowedOverRoaming(false);  
    43.         //设置文件类型  
    44.         MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();  
    45.         String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(apkUrl));  
    46.         request.setMimeType(mimeString);  
    47.         //在通知栏中显示  
    48.         request.setNotificationVisibility(request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  
    49.         request.setTitle("download...");  
    50.         request.setVisibleInDownloadsUi(true);  
    51.         //sdcard目录下的download文件夹  
    52.         request.setDestinationInExternalPublicDir("/download""downloadtest.apk");  
    53.         // 将下载请求放入队列  
    54.          downloadManager.enqueue(request);  
    55.     }  
    56.   
    57.     private BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {  
    58.         @Override  
    59.         public void onReceive(Context context, Intent intent) {  
    60.             /**下载完成后安装APK**/  
    61.             installApk();  
    62.         }  
    63.     };  
    64.   
    65.     private void installApk() {  
    66.         Intent i = new Intent(Intent.ACTION_VIEW);  
    67.         String filePath = "/sdcard/download/downloadtest.apk";  
    68.         i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");  
    69.         startActivity(i);  
    70.     }  
    71. }  


    [java] view plain copy
    1. package com.cardvalue.sys.activitys;  
    2.   
    3. import java.io.File;  
    4. import java.io.UnsupportedEncodingException;  
    5. import java.net.URLEncoder;  
    6. import java.util.Date;  
    7. import java.util.Map;  
    8. import java.util.Set;  
    9.   
    10. import android.annotation.SuppressLint;  
    11. import android.app.DownloadManager;  
    12. import android.app.ProgressDialog;  
    13. import android.content.BroadcastReceiver;  
    14. import android.content.Context;  
    15. import android.content.Intent;  
    16. import android.content.IntentFilter;  
    17. import android.database.Cursor;  
    18. import android.net.ConnectivityManager;  
    19. import android.net.NetworkInfo;  
    20. import android.net.Uri;  
    21. import android.os.Bundle;  
    22. import android.text.TextUtils;  
    23. import android.view.View;  
    24. import android.view.View.OnClickListener;  
    25. import android.view.Window;  
    26. import android.view.WindowManager;  
    27. import android.widget.Button;  
    28. import android.widget.ImageView;  
    29. import android.widget.RelativeLayout;  
    30. import cn.jpush.android.api.InstrumentedActivity;  
    31. import cn.jpush.android.api.JPushInterface;  
    32. import cn.jpush.android.api.TagAliasCallback;  
    33.   
    34. import com.cardvlaue.sys.R;  
    35. import com.cardvalue.sys.annotation.EControl;  
    36. import com.cardvalue.sys.annotation.EventType;  
    37. import com.cardvalue.sys.annotation.FCallHandler;  
    38. import com.cardvalue.sys.annotation.FControl;  
    39. import com.cardvalue.sys.common.CMessage;  
    40. import com.cardvalue.sys.common.MD5Util;  
    41. import com.cardvalue.sys.common.MessageBox;  
    42. import com.cardvalue.sys.common.MyApplication;  
    43. import com.cardvalue.sys.newnetwork.BusinessServices;  
    44. import com.cardvalue.sys.newnetwork.Config;  
    45. import com.cardvalue.sys.newnetwork.Convert;  
    46. import com.cardvalue.sys.newnetwork.CustomHandler;  
    47. import com.cardvalue.sys.newnetwork.UserServices;  
    48. import com.cardvalue.sys.newnetwork.Utiltools;  
    49. import com.cardvalue.sys.widget.WelcomeDialog;  
    50. import com.cardvalue.sys.widget.WelcomeDialog.onAttendOrNotListener;  
    51. import com.cardvalue.sys.widget.WelcomeDialog.onCancelListener;  
    52.   
    53. //import com.tencent.stat.StatService;  
    54.   
    55. /** 
    56.  * 欢迎页面 
    57.  */  
    58. public class WelcomeActivity extends InstrumentedActivity {  
    59.     private Map<String, Object> active = null// 活动页的相关信息  
    60.     private Map<String, Object> showIcon = null// 首页显示的图标  
    61.     public CustomHandler handler;  
    62.     public ProgressDialog dialog;  
    63.     public UserServices userService = new UserServices();  
    64.     public BusinessServices businessService = new BusinessServices();  
    65.   
    66.     @Override  
    67.     protected void onCreate(Bundle savedInstanceState) {  
    68.         super.onCreate(savedInstanceState);  
    69.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
    70.         getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  
    71.                 WindowManager.LayoutParams.FLAG_FULLSCREEN);  
    72.         setContentView(R.layout.welcome);  
    73.         // StatService.trackCustomEvent(this, "onCreate", "");  
    74.         EControl control = new EControl(this);  
    75.         control.setOnClickLisenner(clickLinstenner); // 设置所有的点击事件  
    76.         control.InitControl(); // 开始初始化控件  
    77.         handler = new CustomHandler(this); // 初始化handler  
    78.         dialog = new ProgressDialog(this);  
    79.         JPushInterface.init(getApplicationContext());  
    80.         Utiltools.printE("Jpush data=========>"  
    81.                 + JPushInterface.getRegistrationID(this));  
    82.         handler.sendMessage(handler.obtainMessage(MSG_SET_ALIAS, "android"));  
    83.   
    84.         userService.setValue(this, handler, CMessage.NET_MSG_GETNEWVERSION);  
    85.         if (hasNetworkAvailable()) {  
    86.             userService.getVersionInformation();  
    87.         } else {  
    88.             MessageBox.ToastShow("没有可用网络连接,请检查你的网络!", WelcomeActivity.this);  
    89.             // 没有网络的时候直接到home页  
    90.             handler.sendEmptyMessageDelayed(NORMAL_MSG_HOME, 3000);  
    91.         }  
    92.     }  
    93.   
    94.     /*********************************************************************************************************************************************** 
    95.      * 定义控件,并指定控件对应的ID 
    96.      ***********************************************************************************************************************************************/  
    97.     @FControl(id = R.id.imageView1)  
    98.     public ImageView bg1; // 第一张背景图  
    99.     @FControl(id = R.id.imageView2, eventType = EventType.ON_CLICK)  
    100.     public ImageView bg2; // 第二张背景图  
    101.     @FControl(id = R.id.btn, eventType = EventType.ON_CLICK)  
    102.     public Button button; // 跳过按钮  
    103.     @FControl(id = R.id.ry_wecome)  
    104.     public RelativeLayout wLayout; // 第二张背景图及按钮的布局  
    105.   
    106.     /********************************************************************************************************************************************* 
    107.      * 处理所有的onclick事件 
    108.      *********************************************************************************************************************************************/  
    109.     public OnClickListener clickLinstenner = new OnClickListener() {  
    110.   
    111.         @Override  
    112.         public void onClick(View v) {  
    113.             switch (v.getId()) {  
    114.             case R.id.imageView2: // 按下了活动图片后触发  
    115.                 String isForward = (String) active.get("forwardType"); // 判断是否跳转  
    116.                 if (isForward.equals("1")) {  
    117.                     handler.removeMessages(NORMAL_MSG_LOGIN);  
    118.                     Intent intent = new Intent(WelcomeActivity.this,  
    119.                             LoadWebPage.class);  
    120.                     intent.putExtra("title""活动规则");  
    121.                     intent.putExtra("welcome""welcome");  
    122.                     intent.putExtra("url", (String) active.get("forwordUrl"));  
    123.                     startActivity(intent);  
    124.                     WelcomeActivity.this.finish();  
    125.                 }  
    126.                 break;  
    127.   
    128.             case R.id.btn: // 按下了跳过按钮  
    129.                 handler.removeMessages(NORMAL_MSG_LOGIN);  
    130.                 startActivity(new Intent(WelcomeActivity.this, Home.class));  
    131.                 WelcomeActivity.this.finish();  
    132.                 break;  
    133.             }  
    134.         }  
    135.     };  
    136.   
    137.     /** 
    138.      * 获取最新的服务器版本信息 
    139.      */  
    140.     @SuppressWarnings("unchecked")  
    141.     @FCallHandler(id = CMessage.NET_MSG_GETNEWVERSION)  
    142.     public void getNewVersion() {  
    143.         handler.tempMap = (Map<String, Object>) handler.resultMap  
    144.                 .get("resultData");  
    145.         int clientCode = Utiltools.getAppVersionCode(this); // 客户端的版本code  
    146.         int serverCode = Integer.parseInt(handler.tempMap.get("versionCode")  
    147.                 .toString()); // 服务端的版本code  
    148.         final String isForceUpdate = handler.tempMap.get("isForceUpdate")  
    149.                 .toString(); // 是否强制更新 0不强制更新(可以选择) 1:必须更新  
    150.         active = (Map<String, Object>) handler.tempMap.get("welecomeSet");  
    151.         Utiltools.printE("handler.tempMap" + "=====" + handler.tempMap);  
    152.   
    153.         Utiltools.printE("Convert.convertMap(active).size()" + "====="  
    154.                 + Convert.convertMap(active).size());  
    155.         if (Convert.convertMap(active).size() != 0) {  
    156.             // http://www.cvbaoli.com/webak/resources/newm/images/welcome/welcome640-1136.png  
    157.             String imgUrl = Config.getWeixinIp() + "resources/image/welcome/"  
    158.                     + (String) active.get("picName") + "640-1136."  
    159.                     + (String) active.get("suffix");  
    160.             Utiltools.loadPic(this, imgUrl, bg2, R.drawable.welcome2,  
    161.                     R.drawable.welcome2); // 加载网络图片  
    162.             Utiltools.printE("imgUrlimgUrl");  
    163.         } else {  
    164.             Utiltools.loadPic(this"", bg2, R.drawable.welcome2,  
    165.                     R.drawable.welcome2);  
    166.             Utiltools.printE("imgUrlimgUrl" + "===4444===");  
    167.         }  
    168.         // msg 中的内容根据是否强制更新的不同而进行改变  
    169.         String msg = isForceUpdate.equals("0") ? Utiltools  
    170.                 .getString(R.string.updateSystem) : Utiltools  
    171.                 .getString(R.string.needUpdateSystem);  
    172.         final WelcomeDialog mwelComeDialog = new WelcomeDialog(  
    173.                 WelcomeActivity.this, msg);  
    174.        if (serverCode > clientCode) {// 服务器大于本地 就要更新  
    175.             onAttendOrNotListener welCome = new onAttendOrNotListener() {  
    176.                 @SuppressLint("NewApi")  
    177.                 @Override  
    178.                 public void AttendOrNot() {  
    179.                     MessageBox.show(dialog, """正在下载最新版本,请稍后...");  
    180.                     String url = handler.tempMap.get("url").toString();  
    181.                     DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);  
    182.                     DownloadManager.Request request = new DownloadManager.Request(  
    183.                             Uri.parse(url));  
    184.                     request.setDestinationInExternalPublicDir("/cardvalue",  
    185.                             "cardvalue.apk");  
    186.                     request.setVisibleInDownloadsUi(true);  
    187.                     request.setTitle("卡得万利");  
    188.                     downloadManager.enqueue(request);  
    189.                 }  
    190.             };  
    191.             onCancelListener onCancel = new onCancelListener() {  
    192.                 @Override  
    193.                 public void Cancel() {  
    194.                     if (isForceUpdate.equals("1")) {  
    195.                         mwelComeDialog.cancel();  
    196.                         WelcomeActivity.this.finish();  
    197.                     } else {  
    198.                         handler.sendEmptyMessage(NORMAL_MSG_START);  
    199.                         mwelComeDialog.cancel();  
    200.                     }  
    201.                 }  
    202.             };  
    203.   
    204.             mwelComeDialog.setOnAttendOrNotListener(welCome);  
    205.             mwelComeDialog.setCancelListener(onCancel);  
    206.             mwelComeDialog.show();  
    207.         } else {  
    208.             handler.sendEmptyMessage(NORMAL_MSG_START);  
    209.         }  
    210.     }  
    211.   
    212.     /** 
    213.      * 开始正常的流程 
    214.      */  
    215.     @FCallHandler(id = NORMAL_MSG_START)  
    216.     public void startProcess() {  
    217.         Utiltools.printE("开始正常的流程=====" + Convert.convertMap(active).size());  
    218.         if (Convert.convertMap(active).size() == 0) {  
    219.             handler.sendEmptyMessageDelayed(NORMAL_MSG_LOGIN, 3000); // 5秒以后进入登录页  
    220.             return;  
    221.         }  
    222.         bg1.setVisibility(View.GONE); // 设置背景1层消失  
    223.         wLayout.setVisibility(View.VISIBLE); // 设置背景层显示  
    224.         bg2.setVisibility(View.VISIBLE); // 设置背景2层的图片显示  
    225.         button.setVisibility(View.VISIBLE); // 设置背景2层的按钮显示  
    226.         handler.sendEmptyMessageDelayed(NORMAL_MSG_LOGIN, 5000); // 5秒以后进入登录页  
    227.     }  
    228.   
    229.     @FCallHandler(id = NORMAL_MSG_HOME)  
    230.     public void home() {  
    231.         startActivity(new Intent(WelcomeActivity.this, Home.class));  
    232.         WelcomeActivity.this.finish();  
    233.     }  
    234.   
    235.     /** 
    236.      * 开始登陆操作 
    237.      */  
    238.     @FCallHandler(id = NORMAL_MSG_LOGIN)  
    239.     public void login() {  
    240.         Utiltools.printE("LOGIN====LOGIN");  
    241.         String username = MyApplication.getApplication().getLocalCache()  
    242.                 .getString("username"); // 获取用户名  
    243.         String password = MyApplication.getApplication().getLocalCache()  
    244.                 .getString("password"); // 获取密码  
    245.         if (username.equals("") || password.equals("")) {  
    246.             startActivity(new Intent(WelcomeActivity.this, Home.class));  
    247.             WelcomeActivity.this.finish();  
    248.             return;  
    249.         }  
    250.   
    251.         String pushId = JPushInterface.getRegistrationID(this);  
    252.         long data = System.currentTimeMillis() / 1000;  
    253.         String pass1 = MD5Util.MD5(MD5Util.MD5(password) + "cvbaoli" + data)  
    254.                 + "|" + data;  
    255.         try {  
    256.             userService.setValue(WelcomeActivity.this, handler,  
    257.                     CMessage.NET_MSG_LOGIN);  
    258.             userService.login(username, URLEncoder.encode(pass1, "utf8"),  
    259.                     "mj_"+pushId, null);  
    260.         } catch (UnsupportedEncodingException e) {  
    261.             e.printStackTrace();  
    262.         }  
    263.     }  
    264.   
    265.     /** 
    266.      * 登陆成功后的操作 
    267.      */  
    268.     @FCallHandler(id = CMessage.NET_MSG_LOGIN)  
    269.     public void loginSuccess() {  
    270.         dialog.cancel();  
    271.         MyApplication.getApplication().setLogin(true);  
    272.         MyApplication.getApplication().getLocalCache()  
    273.                 .putString("exirDate", String.valueOf(new Date().getTime()));  
    274.         startActivity(new Intent(WelcomeActivity.this, Home.class));  
    275.         WelcomeActivity.this.finish();  
    276.     }  
    277.   
    278.     /** 
    279.      * 下载完成后广播接收类 
    280.      */  
    281.     class DownloadCompleteReceiver extends BroadcastReceiver {  
    282.         @SuppressLint("NewApi")  
    283.         @Override  
    284.         public void onReceive(Context context, Intent intent) {  
    285.             if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {  
    286.                 DownloadManager downloadManager = (DownloadManager) context  
    287.                         .getSystemService(Context.DOWNLOAD_SERVICE);  
    288.                 DownloadManager.Query query = new DownloadManager.Query();  
    289.                 query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);  
    290.                 Cursor c = downloadManager.query(query);  
    291.                 // 获取文件名并开始安装  
    292.                 if (c.moveToFirst()) {  
    293.                     String fileName = c.getString(c  
    294.                             .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));  
    295.                     fileName = fileName.replace("file://""");  
    296.                     File file = new File(fileName);  
    297.                     Utiltools.print("weiweina""file = " + fileName);  
    298.                     Intent intent1 = new Intent(Intent.ACTION_VIEW);  
    299.                     intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    300.                     intent1.setDataAndType(Uri.fromFile(file),  
    301.                             "application/vnd.android.package-archive");  
    302.                     startActivity(intent1);  
    303.                     WelcomeActivity.this.finish();  
    304.                 }  
    305.             }  
    306.         }  
    307.     }  
    308.   
    309.     // 注册广播  
    310.     public DownloadCompleteReceiver receiver = new DownloadCompleteReceiver();  
    311.   
    312.     @Override  
    313.     protected void onResume() {  
    314.         registerReceiver(receiver, new IntentFilter(  
    315.                 DownloadManager.ACTION_DOWNLOAD_COMPLETE));  
    316.         super.onResume();  
    317.     }  
    318.   
    319.     @Override  
    320.     protected void onDestroy() {  
    321.         if (receiver != null)  
    322.             unregisterReceiver(receiver);  
    323.         super.onDestroy();  
    324.     }  
    325.   
    326.     /**************************************************************************************************************************************** 
    327.      * 自定义消息 
    328.      ****************************************************************************************************************************************/  
    329.     private static final int NORMAL_MSG_START = 1// 进入正常流程消息  
    330.     public static final int NORMAL_MSG_LOGIN = 2// 开始进行登陆操作  
    331.     public static final int NORMAL_MSG_HOME = 3// 延迟3秒到首页  
    332.   
    333.     public static final int MSG_SET_ALIAS = 10001;  
    334.     public static final String MESSAGE_RECEIVED_ACTION = "com.cardvlaue.sys.MESSAGE_RECEIVED_ACTION";  
    335.     public static final String KEY_TITLE = "title";  
    336.     public static final String KEY_MESSAGE = "message";  
    337.     public static final String KEY_EXTRAS = "extras";  
    338.   
    339.     private final TagAliasCallback mAliasCallback = new TagAliasCallback() {  
    340.   
    341.         @Override  
    342.         public void gotResult(int code, String alias, Set<String> tags) {  
    343.             switch (code) {  
    344.             case 6002:  
    345.                 if (isConnected(getApplicationContext())) {  
    346.                     handler.sendMessageDelayed(  
    347.                             handler.obtainMessage(MSG_SET_ALIAS, alias),  
    348.                             1000 * 60);  
    349.                 }  
    350.                 break;  
    351.             }  
    352.         }  
    353.     };  
    354.   
    355.     public static boolean isConnected(Context context) {  
    356.         ConnectivityManager conn = (ConnectivityManager) context  
    357.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
    358.         NetworkInfo info = conn.getActiveNetworkInfo();  
    359.         return (info != null && info.isConnected());  
    360.     }  
    361.   
    362.     @FCallHandler(id = MSG_SET_ALIAS)  
    363.     public void setAlias() {  
    364.         Utiltools.print("极光调用了......................");  
    365.         JPushInterface.setAliasAndTags(getApplicationContext(),  
    366.                 (String) handler.msg.obj, null, mAliasCallback);  
    367.     }  
    368.   
    369.     /** 
    370.      * 判断网络是否连接 
    371.      */  
    372.     private boolean hasNetworkAvailable() {  
    373.         ConnectivityManager cm = (ConnectivityManager) this  
    374.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
    375.         if (cm == null) {  
    376.             return false;  
    377.         } else {  
    378.             NetworkInfo[] info = cm.getAllNetworkInfo();  
    379.             if (info != null) {  
    380.                 for (int i = 0; i < info.length; i++) {  
    381.                     if (info[i].getState() == NetworkInfo.State.CONNECTED) {  
    382.                         return true;  
    383.                     }  
    384.                 }  
    385.             }  
    386.         }  
    387.         return false;  
    388.     }  
    389. }  


  • 相关阅读:
    数学基础之梯度
    背包九问心得
    如何判断机器是大端机还是小端机
    Matlab学习 2021年2月10日
    数字信号处理(超浓缩版)第一天
    matlab里的数据类型
    如何学习Matlab的帮助文档?& 如何去编写帮助文档
    fprintf 和 dlmwrite 在写数据时的区别
    lateinit 延迟初始化
    data class 在 Kotlin中的定义
  • 原文地址:https://www.cnblogs.com/hanjun0612/p/9779735.html
Copyright © 2011-2022 走看看