android 自动更新apk版本

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

截图如下:

 

 

代码实现如下:

复制代码
package com.update.apk;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import org.apache.http.HttpEntity;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.json.JSONArray;import org.json.JSONObject;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.app.ProgressDialog;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager.NameNotFoundException;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.util.Log;public class MainActivity extends Activity {    /** Called when the activity is first created. */    String newVerName = "";//新版本名称    int newVerCode = -1;//新版本号    ProgressDialog pd = null;    String UPDATE_SERVERAPK = "ApkUpdateAndroid.apk";    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        if(getServerVer()){            int verCode = this.getVerCode(this);            if(newVerCode>verCode){                doNewVersionUpdate();//更新版本            }else{                notNewVersionUpdate();//提示已是最新版本            }        }    }        /**     * 获得版本号     */    public int getVerCode(Context context){        int verCode = -1;        try {            verCode = context.getPackageManager().getPackageInfo("com.update.apk", 0).versionCode;        } catch (NameNotFoundException e) {            // TODO Auto-generated catch block            Log.e("版本号获取异常", e.getMessage());        }        return verCode;    }        /**     * 获得版本名称     */    public String getVerName(Context context){        String verName = "";        try {            verName = context.getPackageManager().getPackageInfo("com.update.apk", 0).versionName;        } catch (NameNotFoundException e) {            Log.e("版本名称获取异常", e.getMessage());        }        return verName;    }        /**     * 从服务器端获得版本号与版本名称     * @return     */    public boolean getServerVer(){        try {            URL url = new URL("http://10.0.2.2:8080/ApkUpdateService/ver");            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();            httpConnection.setDoInput(true);            httpConnection.setDoOutput(true);            httpConnection.setRequestMethod("GET");            httpConnection.connect();            InputStreamReader reader = new InputStreamReader(httpConnection.getInputStream());            BufferedReader bReader = new BufferedReader(reader);            String json = bReader.readLine();            JSONArray array = new JSONArray(json);            JSONObject jsonObj = array.getJSONObject(0);            newVerCode = Integer.parseInt(jsonObj.getString("verCode"));                    newVerName = jsonObj.getString("verName");        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();            return false;        }         return true;    }        /**     * 不更新版本     */    public void notNewVersionUpdate(){        int verCode = this.getVerCode(this);        String verName = this.getVerName(this);        StringBuffer sb = new StringBuffer();        sb.append("当前版本:");        sb.append(verName);        sb.append(" Code:");        sb.append(verCode);        sb.append("\n已是最新版本,无需更新");        Dialog dialog = new AlertDialog.Builder(this)        .setTitle("软件更新")        .setMessage(sb.toString())        .setPositiveButton("确定", new DialogInterface.OnClickListener() {                        @Override            public void onClick(DialogInterface dialog, int which) {                // TODO Auto-generated method stub                finish();            }        }).create();        dialog.show();    }        /**     * 更新版本     */    public void doNewVersionUpdate(){        int verCode = this.getVerCode(this);        String verName = this.getVerName(this);        StringBuffer sb = new StringBuffer();        sb.append("当前版本:");        sb.append(verName);        sb.append(" Code:");        sb.append(verCode);        sb.append(",发现版本:");        sb.append(newVerName);        sb.append(" Code:");        sb.append(verCode);        sb.append(",是否更新");        Dialog dialog = new AlertDialog.Builder(this)        .setTitle("软件更新")        .setMessage(sb.toString())        .setPositiveButton("更新", new DialogInterface.OnClickListener() {                        @Override            public void onClick(DialogInterface dialog, int which) {                // TODO Auto-generated method stub                pd = new ProgressDialog(MainActivity.this);                pd.setTitle("正在下载");                pd.setMessage("请稍后。。。");                pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);                downFile("http://10.0.2.2:8080/ApkUpdateService/ApkUpdateAndroid.apk");            }        })        .setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {                        @Override            public void onClick(DialogInterface dialog, int which) {                // TODO Auto-generated method stub                finish();            }        }).create();        //显示更新框        dialog.show();    }        /**     * 下载apk     */    public void downFile(final String url){        pd.show();        new Thread(){            public void run(){                HttpClient client = new DefaultHttpClient();                HttpGet get = new HttpGet(url);                HttpResponse response;                try {                    response = client.execute(get);                    HttpEntity entity = response.getEntity();                    long length = entity.getContentLength();                    InputStream is =  entity.getContent();                    FileOutputStream fileOutputStream = null;                    if(is != null){                        File file = new File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK);                        fileOutputStream = new FileOutputStream(file);                        byte[] b = new byte[1024];                        int charb = -1;                        int count = 0;                        while((charb = is.read(b))!=-1){                            fileOutputStream.write(b, 0, charb);                            count += charb;                        }                    }                    fileOutputStream.flush();                    if(fileOutputStream!=null){                        fileOutputStream.close();                    }                    down();                }  catch (Exception e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }.start();    }        Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);                            pd.cancel();            update();        }    };        /**     * 下载完成,通过handler将下载对话框取消     */    public void down(){        new Thread(){            public void run(){                Message message = handler.obtainMessage();                handler.sendMessage(message);            }        }.start();    }        /**     * 安装应用     */    public void update(){        Intent intent = new Intent(Intent.ACTION_VIEW);        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK))                , "application/vnd.android.package-archive");        startActivity(intent);    }}  
复制代码

 

地址:http://www.cnblogs.com/shmily0703/archive/2012/04/19/shmily_apk_update.html


<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow
这里写图片描述
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
智慧校园整体解决方案是响应国家教育信息化政策,结合教育改革和技术创新的产物。该方案以物联网、大数据、人工智能和移动互联技术为基础,旨在打造一个安全、高效、互动且环保的教育环境。方案强调从数字化校园向智慧校园的转变,通过自动数据采集、智能分析和按需服务,实现校园业务的智能化管理。 方案的总体设计原则包括应用至上、分层设计和互联互通,确保系统能够满足不同用户角色的需求,并实现数据和资源的整合与共享。框架设计涵盖了校园安全、管理、教学、环境等多个方面,构建了一个全面的校园应用生态系统。这包括智慧安全系统、校园身份识别、智能排课及选课系统、智慧学习系统、精品录播教室方案等,以支持个性化学习和教学评估。 建设内容突出了智慧安全和智慧管理的重要性。智慧安全管理通过分布式录播系统和紧急预案一键启动功能,增强校园安全预警和事件响应能力。智慧管理系统则利用物联网技术,实现人员和设备的智能管理,提高校园运营效率。 智慧教学部分,方案提供了智慧学习系统和精品录播教室方案,支持专业级学习硬件和智能化网络管理,促进个性化学习和教学资源的高效利用。同,教学质量评估中心和资源应用平台的建设,旨在提升教学评估的科学性和教育资源的共享性。 智慧环境建设则侧重于基于物联网的设备管理,通过智慧教室管理系统实现教室环境的智能控制和能效管理,打造绿色、节能的校园环境。电子班牌和校园信息发布系统的建设,将作为智慧校园的核心和入口,提供教务、一卡通、图书馆等系统的集成信息。 总体而言,智慧校园整体解决方案通过集成先进技术,不仅提升了校园的信息化水平,而且优化了教学和管理流程,为学生、教师和家长提供了更加便捷、个性化的教育体验。
Android 在切入后台后会暂停所有正在进行的操作,包括 APK 的安装过程。因此,如果用户在 APK 安装过程中切入后台,那么 APK 安装过程会被暂停。 如果你想让 APK 在切入后台后自动安装,可以考虑使用服务来安装 APK。具体来说,你可以在服务中使用 Intent 来启动系统的安装程序来安装 APK。这样,即使用户切入后台,服务仍然在后台运行,安装程序也会在后台自动安装 APK。 下面是一个示例代码,用于在服务中安装 APK: ``` public class ApkInstallService extends Service { private String mApkFilePath; @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { mApkFilePath = intent.getStringExtra("apk_file_path"); if (mApkFilePath != null) { installApk(); } } return super.onStartCommand(intent, flags, startId); } private void installApk() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(mApkFilePath)), "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } ``` 在你的 Activity 中,你可以通过以下代码来启动服务: ``` Intent intent = new Intent(this, ApkInstallService.class); intent.putExtra("apk_file_path", "your_apk_file_path"); startService(intent); ``` 这样,即使用户在 APK 安装过程中切入后台,服务仍然会在后台运行,安装程序也会在后台自动安装 APK
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值