DBMNG数据库管理与应用

独立思考能力,对于从事科学研究或其他任何工作,都是十分必要的。
当前位置:首页 > 移动应用 > Android

获得Android系统所有已安装的应用并联网自动检测升级更新

一、  说明:

本示例是在上一个示例(Android应用自身升级)的基础上完成的。环境配置也同上一个demo一样。只是增加了一些功能用来检测Android系统中所有需要升级的应用程序,并从服务器上下载更新。

二、 功能需求说明:

         a)    检测出Android系统中所有已安装的应用(区别与Android系统自带的应用),并获得每个应用的信息。

         b)    根据上一步获得的系统中已安装的应用信息,通过http连接tomcat7服务器,检测每个应用的代码版本并与当前应用的代码版本进行比较,然后将需要更新的应用显示                    在ListView中。

         c)     在ListView的onItemClick事件中提示是否下载并更新当前的应用。

         d)    监听系统的程序安装和替换广播,当收到系统中有程序安装或替换时,刷新当前的ListView视图以及Activity的标题(Activity的标题用于提示当前需要更新的应用程序数量)。

三、  应用需求的前提假设:

          a)    服务器端的配置

                 在tomcat7服务器的根目录下新建AppUpdate目录,作为更新程序访问的根目录。

          b)    Apk文件的下载路径的标准假设

               在搜寻到系统所有用户安装的应用后,需要访问服务器中对应的每一个应用的version.json配置文件,进行代码版本的比较。该搜寻路径的标准规则我们假定为:

               系统当前安装的每一个应用对应的新版本所在的路径为:

               http://10.0.2.2:8080/AppUpdate/应用程序名/version.json,其中的应用程序名与当前安装的应用程序名相对应,鉴于应用程序名中可能包含‘.’和空格(目前只发现这两                 种情况),我们将应用程序名中所有的‘.’和空格都以下划线代替。例如:

              我们搜到系统中当前已安装的应用名为Sample Soft Keyboard的应用(包含空格),服务器中对应的version.json文件的远程路径为:

              http://10.0.2.2:8080/AppUpdate/Sample_Soft_Keyboard/version.json,(Sample,Soft,Keyboard之间有下划线),对应的新的Apk文件的远程路径为:

              http://10.0.2.2:8080/AppUpdate/Sample_Soft_Keyboard/Sample_Soft_Keyboard.apk

四、  流程以及关键技术说明:

        1) 首先要扫描出系统所有的应用信息,并过滤掉系统自带的应用,只保存用户安装的应用。代码示例:


[java] view plaincopy
  1. public void scanNeedUpdateApp(){  
  2.         List<PackageInfo> appPackage = getPackageManager().getInstalledPackages(0);//获得系统所有应用的安装包信息   
  3.         for(int i=0; i<appPackage.size(); i++){  
  4.             PackageInfo packageInfo = appPackage.get(i);  
  5.             ApplicationInfo tmpAppInfo = new ApplicationInfo();  
  6.             tmpAppInfo.appName = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();  
  7.             tmpAppInfo.packageName = packageInfo.packageName;  
  8.             tmpAppInfo.versionName = packageInfo.versionName;  
  9.             tmpAppInfo.versionCode = packageInfo.versionCode;  
  10.             tmpAppInfo.appIcon = packageInfo.applicationInfo.loadIcon(getPackageManager());  
  11.             //只添加非系统应用   
  12.             if((packageInfo.applicationInfo.flags & android.content.pm.ApplicationInfo.FLAG_SYSTEM) == 0){  
  13.                 String appName = tmpAppInfo.appName.toString().replace('.'' ');  
  14.                 String VerJSONPath =webServicePath + appName +"/" +"version.json";  
  15.                 VerJSONPath = VerJSONPath.replaceAll(" ""_");//拼接对应的version.json的访问路径   
  16.                 System.out.println(VerJSONPath);  
  17.                 try {  
  18.                     JSONObject jsonObj = GetNewVersionCode.getVersionJSON(VerJSONPath);  
  19.                     if(jsonObj != null){  
  20.                         Log.i("JSONnotNull","json 不为空!");  
  21.                         int newVersionCode = Integer.parseInt(jsonObj.getString("versionCode"));  
  22.                         System.out.print("旧代码版本");  
  23.                         System.out.println(tmpAppInfo.versionCode);  
  24.                         System.out.print("新代码版本");  
  25.                         System.out.println(newVersionCode);  
  26.                         if(tmpAppInfo.versionCode < newVersionCode){  
  27.                             tmpAppInfo.newVersionCode = newVersionCode;  
  28.                             tmpAppInfo.newVersionName = jsonObj.getString("versionName");  
  29.                             needUpdateList.add(tmpAppInfo);//将第三方的应用添加到列表中   
  30.                         }  
  31.                     }  
  32.                 } catch (Exception e) {  
  33.                     // TODO Auto-generated catch block   
  34.                     e.printStackTrace();  
  35.                 }  
  36.             }  
  37.         }  
  38.     }  
[java] view plaincopy
  1. public void scanNeedUpdateApp(){  
  2.         List<PackageInfo> appPackage = getPackageManager().getInstalledPackages(0);//获得系统所有应用的安装包信息  
  3.         for(int i=0; i<appPackage.size(); i++){  
  4.             PackageInfo packageInfo = appPackage.get(i);  
  5.             ApplicationInfo tmpAppInfo = new ApplicationInfo();  
  6.             tmpAppInfo.appName = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();  
  7.             tmpAppInfo.packageName = packageInfo.packageName;  
  8.             tmpAppInfo.versionName = packageInfo.versionName;  
  9.             tmpAppInfo.versionCode = packageInfo.versionCode;  
  10.             tmpAppInfo.appIcon = packageInfo.applicationInfo.loadIcon(getPackageManager());  
  11.             //只添加非系统应用  
  12.             if((packageInfo.applicationInfo.flags & android.content.pm.ApplicationInfo.FLAG_SYSTEM) == 0){  
  13.                 String appName = tmpAppInfo.appName.toString().replace('.'' ');  
  14.                 String VerJSONPath =webServicePath + appName +"/" +"version.json";  
  15.                 VerJSONPath = VerJSONPath.replaceAll(" ""_");//拼接对应的version.json的访问路径  
  16.                 System.out.println(VerJSONPath);  
  17.                 try {  
  18.                     JSONObject jsonObj = GetNewVersionCode.getVersionJSON(VerJSONPath);  
  19.                     if(jsonObj != null){  
  20.                         Log.i("JSONnotNull","json 不为空!");  
  21.                         int newVersionCode = Integer.parseInt(jsonObj.getString("versionCode"));  
  22.                         System.out.print("旧代码版本");  
  23.                         System.out.println(tmpAppInfo.versionCode);  
  24.                         System.out.print("新代码版本");  
  25.                         System.out.println(newVersionCode);  
  26.                         if(tmpAppInfo.versionCode < newVersionCode){  
  27.                             tmpAppInfo.newVersionCode = newVersionCode;  
  28.                             tmpAppInfo.newVersionName = jsonObj.getString("versionName");  
  29.                             needUpdateList.add(tmpAppInfo);//将第三方的应用添加到列表中  
  30.                         }  
  31.                     }  
  32.                 } catch (Exception e) {  
  33.                     // TODO Auto-generated catch block  
  34.                     e.printStackTrace();  
  35.                 }  
  36.             }  
  37.         }  
  38.     }  

       说明: 获得已安装的应用程序信息 可以通过getPackageManager()方法获得

       Public abstract PackageManager  getPackageManager(), 然后将所有已安装的包信息放入List<PackageInfo>泛型中。方法如下

       Public abstract List<PackageInfo>  getInstalledPackages(int flags)

       过滤第三方应用,所有的系统应用的flag标志为FALG_SYSTEM(值为1),第三方的应用为flag标志的值为0

  2)   填充ListView的adapter数据集,并刷新ListView,代码示例如下:


[java] view plaincopy
  1. //填充ListView   
  2.     public void fillListView(){  
  3.         ListView newUpdateListView = (ListView)findViewById(R.id.listview);  
  4.         appAdapter =new NeedUpdateListAdapter(this,needUpdateList);//填充adapter数据集   
  5.         newUpdateListView.setDividerHeight(5);  
  6.         if(!appAdapter.isEmpty()){  
  7.             int needUpdateCount = appAdapter.getCount();  
  8.             setTitle("当前发现"+needUpdateCount + "款应用需要升级!");  
  9.             newUpdateListView.setAdapter(appAdapter);//填充ListView   
  10.             newUpdateListView.setOnItemClickListener(this);//设置ListView中Item的单击事件   
  11.         }else{                    
  12.             setTitle("未发现需要升级的应用!");  
  13.         }  
  14.     }  
[java] view plaincopy
  1. //填充ListView  
  2.     public void fillListView(){  
  3.         ListView newUpdateListView = (ListView)findViewById(R.id.listview);  
  4.         appAdapter =new NeedUpdateListAdapter(this,needUpdateList);//填充adapter数据集  
  5.         newUpdateListView.setDividerHeight(5);  
  6.         if(!appAdapter.isEmpty()){  
  7.             int needUpdateCount = appAdapter.getCount();  
  8.             setTitle("当前发现"+needUpdateCount + "款应用需要升级!");  
  9.             newUpdateListView.setAdapter(appAdapter);//填充ListView  
  10.             newUpdateListView.setOnItemClickListener(this);//设置ListView中Item的单击事件  
  11.         }else{                    
  12.             setTitle("未发现需要升级的应用!");  
  13.         }  
  14.     }  


   3)   注册一个Handler用于在ListView刷新之后,刷新ListView所在的Activity的标题(用于显示当前剩余的需要更新的应用数量)代码示例:


[java] view plaincopy
  1. //注册refreshTitleHandler,用于在广播接收中更新Activity的标题   
  2.     public void registerRefreshTitleHandler(){  
  3.         refreshTitleHandler = new Handler(){  
  4.             public void handleMessage(Message msg){  
  5.                 switch(msg.what){  
  6.                 case 0:setTitle("当前发现"+appAdapter.getCount()+"款应用需要升级");break;  
  7.                 }  
  8.                 super.handleMessage(msg);  
  9.             }  
  10.         };  
  11.     }  
[java] view plaincopy
  1. //注册refreshTitleHandler,用于在广播接收中更新Activity的标题  
  2.     public void registerRefreshTitleHandler(){  
  3.         refreshTitleHandler = new Handler(){  
  4.             public void handleMessage(Message msg){  
  5.                 switch(msg.what){  
  6.                 case 0:setTitle("当前发现"+appAdapter.getCount()+"款应用需要升级");break;  
  7.                 }  
  8.                 super.handleMessage(msg);  
  9.             }  
  10.         };  
  11.     }  


   4)   监听系统中应用程序的安装和替换广播,并在广播接收中刷新ListView

         说明:因为在新版本的应用下载更新时会进入系统自带的安装程序,所以我们要监听系统发送的有应用程序安装或者替换的广播

        (”android.intent.action.PACKAGE_REPLACED”),并在广播接收函数onReceiver()中处理刷新ListView视图,这就涉及到不同的类中更新UI界面的问题。在这里我们的           解决方案是在接收到广播刷新ListView后向Activity的Handle发送一个消息,用于更新Activity的标题。(Handle我们设置成全局静态的方便引用)。代码示例如下:


[java] view plaincopy
  1. public class RefreshListViewBroadcastReceiver extends BroadcastReceiver {  
  2.     @Override  
  3.     public void onReceive(Context context, Intent intent) {  
  4.         // TODO Auto-generated method stub   
  5.         Log.i("Broadcast""我是广播");  
  6.         if(intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")){  
  7.             //获取被替换的包名,因为getDataString()返回的值包含了“package:“,所以要从第八的位置开始截取   
  8.             String replacedPackageName =intent.getDataString().substring(8);  
  9.             if(!context.getPackageName().equals(replacedPackageName)){  
  10.                 Log.i("curPackName",context.getPackageName());  
  11.                 System.out.print(replacedPackageName);  
  12.                 Log.i("replacedPack",replacedPackageName);  
  13.                 if(CheckUpdateAllActivity.appAdapter.remove(replacedPackageName)){  
  14.                     //刷新主Activity的Titlt   
  15.                     Message message = new Message();  
  16.                     message.what = 0;  
  17.                     CheckUpdateAllActivity.refreshTitleHandler.sendMessage(message);  
  18.                 }  
  19.             }  
  20.         }  
  21.     }  
  22. }  
[java] view plaincopy
  1. public class RefreshListViewBroadcastReceiver extends BroadcastReceiver {  
  2.     @Override  
  3.     public void onReceive(Context context, Intent intent) {  
  4.         // TODO Auto-generated method stub  
  5.         Log.i("Broadcast""我是广播");  
  6.         if(intent.getAction().equals("android.intent.action.PACKAGE_REPLACED")){  
  7.             //获取被替换的包名,因为getDataString()返回的值包含了“package:“,所以要从第八的位置开始截取  
  8.             String replacedPackageName =intent.getDataString().substring(8);  
  9.             if(!context.getPackageName().equals(replacedPackageName)){  
  10.                 Log.i("curPackName",context.getPackageName());  
  11.                 System.out.print(replacedPackageName);  
  12.                 Log.i("replacedPack",replacedPackageName);  
  13.                 if(CheckUpdateAllActivity.appAdapter.remove(replacedPackageName)){  
  14.                     //刷新主Activity的Titlt  
  15.                     Message message = new Message();  
  16.                     message.what = 0;  
  17.                     CheckUpdateAllActivity.refreshTitleHandler.sendMessage(message);  
  18.                 }  
  19.             }  
  20.         }  
  21.     }  
  22. }  


         进一步说明:广播接收的注册方式有两种,一种是静态注册(在xml文件中),另一种是动态注册(在代码中),二者的区别在于:生命周期不一样。若以静态方式注册               的广播,在第一次注册之后就与其所在的应用程序无关了,即在应用程序退出后,系统仍然能接受到该广播(若在应用程序退出后有该广播发出)。以动态方式注册的广            播与程序有关,即程序退出后,就无法处理对应的广播了。示例中接受系统程序是否被替换的广播会监听自身的替换(重新RunAs),所以我们要屏蔽掉自身的替换,如            果不屏蔽的话在开始RunAs自己后(监听了自己)会找不到程序中的appAdapter(因为程序还没开始运行)而报出空指针异常的现象。所以我们根据上下文(context)来          获得当前应用的包名,并与此时被替换的包名(通过intent来获得)作比较来过滤掉自身的监听。

   5)   ListView的Item单击事件。ListView中显示的Item代表可升级的应用程序,若用户单击Item项后,弹出是否更新的对话框。


[java] view plaincopy
  1. //ListView中Item的单击事件   
  2.     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
  3.         // TODO Auto-generated method stub   
  4.         ApplicationInfo clickedItemInfo = (ApplicationInfo) appAdapter.getItem(position);  
  5.         curClickItemAppName = clickedItemInfo.appName;  
  6.         StringBuffer sb = new StringBuffer();  
  7.         Log.i("adapterVerName",clickedItemInfo.versionName);  
  8.         sb.append("当前版本:" + "\n");  
  9.         sb.append("版本名称:" + clickedItemInfo.versionName);  
  10.         sb.append("版本代码:" + clickedItemInfo.versionCode + "\n");  
  11.         sb.append("发现新版本:" + "\n");  
  12.         sb.append("版本名称:" + clickedItemInfo.newVersionName);  
  13.         sb.append("版本代码:" + clickedItemInfo.newVersionCode + "\n");  
  14.         sb.append("是否更新?");  
  15.         Dialog dialog = new AlertDialog.Builder(CheckUpdateAllActivity.this)  
  16.         .setTitle("软件更新")  
  17.         .setMessage(sb.toString())  
  18.         .setPositiveButton("立即更新"new DialogInterface.OnClickListener() {  
  19.               
  20.             @Override  
  21.             public void onClick(DialogInterface dialog, int which) {  
  22.                 // TODO Auto-generated method stub   
  23.                 if(curClickItemAppName != ""){  
  24.                     String appName = curClickItemAppName.replace('.'' ');  
  25.                     String loadUrl = webServicePath + appName +"/" +appName +".apk";  
  26.                     loadUrl = loadUrl.replaceAll(" ""_");  
  27.                     Log.i("LoadUrl", loadUrl);  
  28.                     downLoadApkFile(loadUrl, appName);  
  29.                 }else{  
  30.                     curClickItemAppName = "";  
  31.                 }  
  32.             }  
  33.         })  
  34.         .setNegativeButton("暂不更新"new DialogInterface.OnClickListener() {  
  35.               
  36.             @Override  
  37.             public void onClick(DialogInterface dialog, int which) {  
  38.                 // TODO Auto-generated method stub   
  39.                 curClickItemAppName = "";  
  40.             }  
  41.         }).create();  
  42.         dialog.show();  
  43.     }  
[java] view plaincopy
  1. //ListView中Item的单击事件  
  2.     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
  3.         // TODO Auto-generated method stub  
  4.         ApplicationInfo clickedItemInfo = (ApplicationInfo) appAdapter.getItem(position);  
  5.         curClickItemAppName = clickedItemInfo.appName;  
  6.         StringBuffer sb = new StringBuffer();  
  7.         Log.i("adapterVerName",clickedItemInfo.versionName);  
  8.         sb.append("当前版本:" + "\n");  
  9.         sb.append("版本名称:" + clickedItemInfo.versionName);  
  10.         sb.append("版本代码:" + clickedItemInfo.versionCode + "\n");  
  11.         sb.append("发现新版本:" + "\n");  
  12.         sb.append("版本名称:" + clickedItemInfo.newVersionName);  
  13.         sb.append("版本代码:" + clickedItemInfo.newVersionCode + "\n");  
  14.         sb.append("是否更新?");  
  15.         Dialog dialog = new AlertDialog.Builder(CheckUpdateAllActivity.this)  
  16.         .setTitle("软件更新")  
  17.         .setMessage(sb.toString())  
  18.         .setPositiveButton("立即更新"new DialogInterface.OnClickListener() {  
  19.               
  20.             @Override  
  21.             public void onClick(DialogInterface dialog, int which) {  
  22.                 // TODO Auto-generated method stub  
  23.                 if(curClickItemAppName != ""){  
  24.                     String appName = curClickItemAppName.replace('.'' ');  
  25.                     String loadUrl = webServicePath + appName +"/" +appName +".apk";  
  26.                     loadUrl = loadUrl.replaceAll(" ""_");  
  27.                     Log.i("LoadUrl", loadUrl);  
  28.                     downLoadApkFile(loadUrl, appName);  
  29.                 }else{  
  30.                     curClickItemAppName = "";  
  31.                 }  
  32.             }  
  33.         })  
  34.         .setNegativeButton("暂不更新"new DialogInterface.OnClickListener() {  
  35.               
  36.             @Override  
  37.             public void onClick(DialogInterface dialog, int which) {  
  38.                 // TODO Auto-generated method stub  
  39.                 curClickItemAppName = "";  
  40.             }  
  41.         }).create();  
  42.         dialog.show();  
  43.     }  


        说明:被单击的Item对应的应用程序信息的获取通过getItem(position)来完成,该函数返回的对象类型即Adapter中保存的数据类型,强转一下就可以了。之后就是按照           我们事先约定的新版本Apk的远程访问路径规则来拼接Apk的下载路径了。


     6)    下载新版本的apk文件。这一步没什么好说的了,上一篇已经很详细了(Android单个应用自身的升级)示例如下:


[java] view plaincopy
  1. //下载新的apk应用文件   
  2.     protected void downLoadApkFile(final String url, final String appName) {  
  3.         // TODO Auto-generated method stub   
  4.         pBar = new ProgressDialog(CheckUpdateAllActivity.this);  
  5.         pBar.setTitle("正在下载");  
  6.         pBar.setMessage("请稍候...");  
  7.         pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);  
  8.         pBar.show();  
  9.         new Thread(){  
  10.             public void run(){  
  11.                 HttpClient httpClient = new DefaultHttpClient();  
  12.                 HttpGet httpGet = new HttpGet(url);  
  13.                 HttpResponse httpResponse;  
  14.                 try {  
  15.                     httpResponse = httpClient.execute(httpGet);  
  16.                     if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){    
  17.                         HttpEntity httpEntity = httpResponse.getEntity();  
  18.                         InputStream is = httpEntity.getContent();  
  19.                         FileOutputStream fos = null;  
  20.                         if(is !=null){  
  21.                             File file = new File(Environment.getExternalStorageDirectory(),appName+".apk");  
  22.                             fos = new FileOutputStream(file);  
  23.                             byte[] buf = new byte[1024];  
  24.                             int ch = -1;  
  25.                             do{  
  26.                                 ch = is.read(buf);  
  27.                                 if(ch <= 0)break;  
  28.                                 fos.write(buf, 0, ch);  
  29.                             }while(true);  
  30.                             is.close();  
  31.                             fos.close();  
  32.                             haveDownLoad(appName + ".apk");  
  33.                         }else{  
  34.                             throw new RuntimeException("isStream is null");  
  35.                         }  
  36.                     }else if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND){  
  37.                         //404未找到相应的文件   
  38.                         Looper.prepare();  
  39.                         Toast toast = Toast.makeText(CheckUpdateAllActivity.this"未找到对应的Apk文件!"1);  
  40.                         pBar.cancel();  
  41.                         toast.show();  
  42.                         Looper.loop();  
  43.                     }  
  44.                 } catch (ClientProtocolException e) {  
  45.                     // TODO Auto-generated catch block   
  46.                     e.printStackTrace();  
  47.                 } catch (IOException e) {  
  48.                     // TODO Auto-generated catch block   
  49.                     e.printStackTrace();  
  50.                 }  
  51.             }  
  52.         }.start();  
  53.     }  
[java] view plaincopy
  1. //下载新的apk应用文件  
  2.     protected void downLoadApkFile(final String url, final String appName) {  
  3.         // TODO Auto-generated method stub  
  4.         pBar = new ProgressDialog(CheckUpdateAllActivity.this);  
  5.         pBar.setTitle("正在下载");  
  6.         pBar.setMessage("请稍候...");  
  7.         pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);  
  8.         pBar.show();  
  9.         new Thread(){  
  10.             public void run(){  
  11.                 HttpClient httpClient = new DefaultHttpClient();  
  12.                 HttpGet httpGet = new HttpGet(url);  
  13.                 HttpResponse httpResponse;  
  14.                 try {  
  15.                     httpResponse = httpClient.execute(httpGet);  
  16.                     if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){    
  17.                         HttpEntity httpEntity = httpResponse.getEntity();  
  18.                         InputStream is = httpEntity.getContent();  
  19.                         FileOutputStream fos = null;  
  20.                         if(is !=null){  
  21.                             File file = new File(Environment.getExternalStorageDirectory(),appName+".apk");  
  22.                             fos = new FileOutputStream(file);  
  23.                             byte[] buf = new byte[1024];  
  24.                             int ch = -1;  
  25.                             do{  
  26.                                 ch = is.read(buf);  
  27.                                 if(ch <= 0)break;  
  28.                                 fos.write(buf, 0, ch);  
  29.                             }while(true);  
  30.                             is.close();  
  31.                             fos.close();  
  32.                             haveDownLoad(appName + ".apk");  
  33.                         }else{  
  34.                             throw new RuntimeException("isStream is null");  
  35.                         }  
  36.                     }else if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND){  
  37.                         //404未找到相应的文件  
  38.                         Looper.prepare();  
  39.                         Toast toast = Toast.makeText(CheckUpdateAllActivity.this"未找到对应的Apk文件!"1);  
  40.                         pBar.cancel();  
  41.                         toast.show();  
  42.                         Looper.loop();  
  43.                     }  
  44.                 } catch (ClientProtocolException e) {  
  45.                     // TODO Auto-generated catch block  
  46.                     e.printStackTrace();  
  47.                 } catch (IOException e) {  
  48.                     // TODO Auto-generated catch block  
  49.                     e.printStackTrace();  
  50.                 }  
  51.             }  
  52.         }.start();  
  53.     }  
         说明:简单的http通信的步骤:1.建立HttpClient客户端。2.创建访问路径HttpGet3.请求连接HttpResponse。通过http请求下载远端的文件时,有可能在所给的访问路径下         没有需要的文件,在这里请求状态通过HttpResponse.getStatusLine().getStatusCode()来获得。常见的请求回应码为200(请求成功),404(未找到对应的文件)。另           外我们在下载子线程中去取消了下载进度条(下载完成后),涉及了在子线程中去更新UI,这样违反了Android系统中UI单线程模型的原则,是不被允许的。所以要用                   Looper或者Handle来处理。此处用了Looper。



    7)   下载完成后提示是否安装,当选择取消后删除sdcard中下载的Apk文件。


[java] view plaincopy
  1. //下载完成 关闭进度条,并提示是否安装   
  2.     protected void haveDownLoad(final String fileName) {  
  3.         // TODO Auto-generated method stub   
  4.         pBar.cancel();//下载完成取消进度条   
  5.         haveDownHandler.post(new Runnable(){  
  6.   
  7.             @Override  
  8.             public void run() {  
  9.                 // TODO Auto-generated method stub   
  10.                 Dialog installDialog = new AlertDialog.Builder(CheckUpdateAllActivity.this)  
  11.                 .setTitle("下载完成")  
  12.                 .setMessage("是否安装新的应用")  
  13.                 .setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  14.                       
  15.                     @Override  
  16.                     public void onClick(DialogInterface dialog, int which) {  
  17.                         // TODO Auto-generated method stub   
  18.                         installNewApk(fileName);  
  19.                     }     
  20.                 })  
  21.                 .setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  22.                       
  23.                     @Override  
  24.                     public void onClick(DialogInterface dialog, int which) {  
  25.                         // TODO Auto-generated method stub   
  26.                         File downLoadApk = new File(Environment.getExternalStorageDirectory(),  
  27.                                 fileName);  
  28.                         if(downLoadApk.exists()){  
  29.                             downLoadApk.delete();  
  30.                         }  
  31.                     }  
  32.                 }).create();  
  33.                 installDialog.show();  
  34.             }  
  35.         });  
  36.     }  
[java] view plaincopy
  1. //下载完成 关闭进度条,并提示是否安装  
  2.     protected void haveDownLoad(final String fileName) {  
  3.         // TODO Auto-generated method stub  
  4.         pBar.cancel();//下载完成取消进度条  
  5.         haveDownHandler.post(new Runnable(){  
  6.   
  7.             @Override  
  8.             public void run() {  
  9.                 // TODO Auto-generated method stub  
  10.                 Dialog installDialog = new AlertDialog.Builder(CheckUpdateAllActivity.this)  
  11.                 .setTitle("下载完成")  
  12.                 .setMessage("是否安装新的应用")  
  13.                 .setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  14.                       
  15.                     @Override  
  16.                     public void onClick(DialogInterface dialog, int which) {  
  17.                         // TODO Auto-generated method stub  
  18.                         installNewApk(fileName);  
  19.                     }     
  20.                 })  
  21.                 .setNegativeButton("取消"new DialogInterface.OnClickListener() {  
  22.                       
  23.                     @Override  
  24.                     public void onClick(DialogInterface dialog, int which) {  
  25.                         // TODO Auto-generated method stub  
  26.                         File downLoadApk = new File(Environment.getExternalStorageDirectory(),  
  27.                                 fileName);  
  28.                         if(downLoadApk.exists()){  
  29.                             downLoadApk.delete();  
  30.                         }  
  31.                     }  
  32.                 }).create();  
  33.                 installDialog.show();  
  34.             }  
  35.         });  
  36.     }  


    8)    调用系统自带的安装程序进行安装。如果想采用静默安装,网上大侠们说要修改源码才可以。


[java] view plaincopy
  1. //安装下载后的应用程序   
  2.     private void installNewApk(final String fileName) {  
  3.         // TODO Auto-generated method stub   
  4.         Intent intent = new Intent(Intent.ACTION_VIEW);  
  5.         intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),fileName)),  
  6.                 "application/vnd.android.package-archive");  
  7.         startActivity(intent);  
  8.     }   
[java] view plaincopy
  1. //安装下载后的应用程序  
  2.     private void installNewApk(final String fileName) {  
  3.         // TODO Auto-generated method stub  
  4.         Intent intent = new Intent(Intent.ACTION_VIEW);  
  5.         intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),fileName)),  
  6.                 "application/vnd.android.package-archive");  
  7.         startActivity(intent);  
  8.     }   


    9)  JSON文件解析类。该类中封装了一个静态方法getVersionJSON()用于获得远程的version.json文件信息,返回对象类型为JSONObject,便于解析出每一个应用对应的           versionCode信息。示例如下:


[java] view plaincopy
  1. public class GetNewVersionCode {  
  2.   
  3.     public static JSONObject getVersionJSON(String VerJSONPath) throws ClientProtocolException, IOException, JSONException{  
  4.         StringBuilder VerJSON = new StringBuilder();  
  5.         HttpClient client = new DefaultHttpClient();  
  6.         HttpParams httpParams = client.getParams();  
  7.         HttpConnectionParams.setConnectionTimeout(httpParams, 3000);  
  8.         HttpConnectionParams.setSoTimeout(httpParams, 5000);  
  9.         HttpResponse response;  
  10.         response = client.execute(new HttpGet(VerJSONPath));  
  11.         //请求成功   
  12.         System.out.print("链接请求码:");  
  13.         System.out.println(response.getStatusLine().getStatusCode());  
  14.         if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
  15.             Log.i("ConOK","链接成功");  
  16.             HttpEntity entity = response.getEntity();  
  17.             if(entity != null){  
  18.                 BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"), 8192);  
  19.                 String line = null;  
  20.                 while((line = reader.readLine()) != null){  
  21.                     VerJSON.append(line+"\n");  
  22.                 }  
  23.                 reader.close();  
  24.                 JSONArray verJSONArray = new JSONArray(VerJSON.toString());  
  25.                 if(verJSONArray.length() > 0){  
  26.                     JSONObject obj = verJSONArray.getJSONObject(0);  
  27.                     return obj;  
  28.                 }  
  29.             }  
  30.               
  31.             Log.i("ContFail","获取JSONObject失败!");  
  32.             return null;  
  33.         }  
  34.         Log.i("ConFail","链接失败!");  
  35.         return null;  
  36.     }  
  37. }  
[java] view plaincopy
  1. public class GetNewVersionCode {  
  2.   
  3.     public static JSONObject getVersionJSON(String VerJSONPath) throws ClientProtocolException, IOException, JSONException{  
  4.         StringBuilder VerJSON = new StringBuilder();  
  5.         HttpClient client = new DefaultHttpClient();  
  6.         HttpParams httpParams = client.getParams();  
  7.         HttpConnectionParams.setConnectionTimeout(httpParams, 3000);  
  8.         HttpConnectionParams.setSoTimeout(httpParams, 5000);  
  9.         HttpResponse response;  
  10.         response = client.execute(new HttpGet(VerJSONPath));  
  11.         //请求成功  
  12.         System.out.print("链接请求码:");  
  13.         System.out.println(response.getStatusLine().getStatusCode());  
  14.         if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
  15.             Log.i("ConOK","链接成功");  
  16.             HttpEntity entity = response.getEntity();  
  17.             if(entity != null){  
  18.                 BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"), 8192);  
  19.                 String line = null;  
  20.                 while((line = reader.readLine()) != null){  
  21.                     VerJSON.append(line+"\n");  
  22.                 }  
  23.                 reader.close();  
  24.                 JSONArray verJSONArray = new JSONArray(VerJSON.toString());  
  25.                 if(verJSONArray.length() > 0){  
  26.                     JSONObject obj = verJSONArray.getJSONObject(0);  
  27.                     return obj;  
  28.                 }  
  29.             }  
  30.               
  31.             Log.i("ContFail","获取JSONObject失败!");  
  32.             return null;  
  33.         }  
  34.         Log.i("ConFail","链接失败!");  
  35.         return null;  
  36.     }  
  37. }  


   10)   与ListView绑定的Adapter类,该类中最主要的方法是getCount()和getView()用于绘制ListView。在这里重写该类的构造方法,以便于在Adapter中保存我们需要的类型            (ApplicationInfo)。示例如下:


[java] view plaincopy
  1. public class NeedUpdateListAdapter extends BaseAdapter {  
  2.   
  3.     Context context;  
  4.     ArrayList<ApplicationInfo> needUpdateList = new ArrayList<ApplicationInfo>();  
  5.     public NeedUpdateListAdapter(Context context, ArrayList<ApplicationInfo> newNeedUpdateList){  
  6.         this.context = context;  
  7.         needUpdateList.clear();  
  8.         for(int i = 0; i<newNeedUpdateList.size(); i++){  
  9.             needUpdateList.add(newNeedUpdateList.get(i));  
  10.         }  
  11.     }  
  12.     @Override  
  13.     public int getCount() {  
  14.         // TODO Auto-generated method stub   
  15.         return needUpdateList.size();  
  16.     }  
  17.   
  18.     @Override  
  19.     public Object getItem(int position) {  
  20.         // TODO Auto-generated method stub   
  21.         return needUpdateList.get(position);  
  22.     }  
  23.   
  24.     @Override  
  25.     public long getItemId(int position) {  
  26.         // TODO Auto-generated method stub   
  27.         return position;  
  28.     }  
  29.   
  30.     @Override  
  31.     public View getView(int position, View convertView, ViewGroup parent) {  
  32.         // TODO Auto-generated method stub   
  33.         View newView = convertView;  
  34.         final ApplicationInfo appItem = needUpdateList.get(position);  
  35.         if(newView == null){  
  36.             LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  37.             newView = vi.inflate(R.layout.check_update_list_item, null);  
  38.             //newView.setClickable(true);加上此句ListViewi点击无响应,不知道是为什么   
  39.         }  
  40.         TextView appName = (TextView)newView.findViewById(R.id.appName);  
  41.         ImageView appIcon=(ImageView)newView.findViewById(R.id.icon);  
  42.         if(appName != null)  
  43.             appName.setText(appItem.appName);  
  44.         if(appIcon != null)  
  45.             appIcon.setImageDrawable(appItem.appIcon);  
  46.         return newView;  
  47.     }  
  48.       
  49.     public  boolean remove(String packageName){  
  50.         boolean flag = false;  
  51.         for(int i = 0; i < needUpdateList.size(); i++){  
  52.             if(needUpdateList.get(i).packageName.equals(packageName)){  
  53.                 needUpdateList.remove(i);  
  54.                 flag = true;  
  55.                 Log.i("RemovePack", packageName);  
  56.                 notifyDataSetChanged();  
  57.             }  
  58.         }  
  59.         if(flag){  
  60.             flag = false;  
  61.             return true;  
  62.         }  
  63.         return false;  
  64.     }  
  65.     public void removeAll(){  
  66.         needUpdateList.clear();  
  67.         notifyDataSetChanged();  
  68.     }  
  69. }  
[java] view plaincopy
  1. public class NeedUpdateListAdapter extends BaseAdapter {  
  2.   
  3.     Context context;  
  4.     ArrayList<ApplicationInfo> needUpdateList = new ArrayList<ApplicationInfo>();  
  5.     public NeedUpdateListAdapter(Context context, ArrayList<ApplicationInfo> newNeedUpdateList){  
  6.         this.context = context;  
  7.         needUpdateList.clear();  
  8.         for(int i = 0; i<newNeedUpdateList.size(); i++){  
  9.             needUpdateList.add(newNeedUpdateList.get(i));  
  10.         }  
  11.     }  
  12.     @Override  
  13.     public int getCount() {  
  14.         // TODO Auto-generated method stub  
  15.         return needUpdateList.size();  
  16.     }  
  17.   
  18.     @Override  
  19.     public Object getItem(int position) {  
  20.         // TODO Auto-generated method stub  
  21.         return needUpdateList.get(position);  
  22.     }  
  23.   
  24.     @Override  
  25.     public long getItemId(int position) {  
  26.         // TODO Auto-generated method stub  
  27.         return position;  
  28.     }  
  29.   
  30.     @Override  
  31.     public View getView(int position, View convertView, ViewGroup parent) {  
  32.         // TODO Auto-generated method stub  
  33.         View newView = convertView;  
  34.         final ApplicationInfo appItem = needUpdateList.get(position);  
  35.         if(newView == null){  
  36.             LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  37.             newView = vi.inflate(R.layout.check_update_list_item, null);  
  38.             //newView.setClickable(true);加上此句ListViewi点击无响应,不知道是为什么  
  39.         }  
  40.         TextView appName = (TextView)newView.findViewById(R.id.appName);  
  41.         ImageView appIcon=(ImageView)newView.findViewById(R.id.icon);  
  42.         if(appName != null)  
  43.             appName.setText(appItem.appName);  
  44.         if(appIcon != null)  
  45.             appIcon.setImageDrawable(appItem.appIcon);  
  46.         return newView;  
  47.     }  
  48.       
  49.     public  boolean remove(String packageName){  
  50.         boolean flag = false;  
  51.         for(int i = 0; i < needUpdateList.size(); i++){  
  52.             if(needUpdateList.get(i).packageName.equals(packageName)){  
  53.                 needUpdateList.remove(i);  
  54.                 flag = true;  
  55.                 Log.i("RemovePack", packageName);  
  56.                 notifyDataSetChanged();  
  57.             }  
  58.         }  
  59.         if(flag){  
  60.             flag = false;  
  61.             return true;  
  62.         }  
  63.         return false;  
  64.     }  
  65.     public void removeAll(){  
  66.         needUpdateList.clear();  
  67.         notifyDataSetChanged();  
  68.     }  
  69. }  


     说明:当每绘制一项时就会调用一次getView()方法,就会装载一次我们建立的布局文件一次(check_update_list_item.xml),在getView方法中设置布局文件中的组件       (TextView和ImageView)就能得到我们想要的视图。另外添加两个方法remove()和removeAll()用于ListView的刷新(当我们下载安装新版本后)。其中                  NotifyDataSetChanged()用于自动刷新ListView。


    11)  应用程序信息类,主要用于保存应用程序的一些信息,如当前应用的程序名,包名,版本名称,版本代码,图标,所搜寻到的新版本的版本名称,新的版本代码。


[java] view plaincopy
  1. public class ApplicationInfo {  
  2.   
  3.     public String appName = "";  
  4.     public String packageName = "";  
  5.     public String versionName = "";  
  6.     public String newVersionName = "";  
  7.     public int versionCode = 0;  
  8.     public int newVersionCode = 0;  
  9.     public Drawable appIcon = null;  
  10.       
  11. }  
[java] view plaincopy
  1. public class ApplicationInfo {  
  2.   
  3.     public String appName = "";  
  4.     public String packageName = "";  
  5.     public String versionName = "";  
  6.     public String newVersionName = "";  
  7.     public int versionCode = 0;  
  8.     public int newVersionCode = 0;  
  9.     public Drawable appIcon = null;  
  10.       
  11. }  



源码下载连接:本篇源码下载

下面是一些效果图:

    将系统所有已安装的应用添加到ListView中

点击更新某一个应用

下载新应用

下载完成提示安装

进入系统安装







更新完成后刷新ListView和Activity标题

当在远程服务器中没有找到对应的apk文件则提示错误。

本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号