版本更新

//今天就让我们来学习一下版本更新
首先我们给出一个按钮实现检验版本号 也就是布局中的代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:onClick="version_check"
        android:layout_centerVertical="true"
        android:text="@string/button" />

</RelativeLayout>

//下面来让我们实现这个按钮的监听事件
也就是我们主类中的代码了

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
/**
 * 版本更新
 * 
 * @author Administrator
 * 
 */
@SuppressLint("InflateParams")
public class MainActivity extends Activity {
    private ProgressBar progressbar1;
    //进度条进度
    private int pregress_cont;
    private GetVersionCode getcode;
    private List<NameValuePair> pair;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getcode = new GetVersionCode();
    }

    //点击事件
    public void version_check(View view){
        pair = new ArrayList<NameValuePair>();
        pair.add(new BasicNameValuePair("", ""));
        new Thread(){
            public void run() {
//              这里发送请求
//              String str = http_post("http://169.254.61.100:8080/1310A/json.txt",pair);
                String str = Httputils.http_post("http://www.baidu.com",pair);
                Log.i("TAG","返回结果=="+str);
                if(null!=str && !str.equals("000")){
                    //这里对返回值进行判断,如果服务器版本大于当前版本,那么久弹出一个框,提示更新
//                  因为请求原因,这里直接弹出一个框,选择下载文件
                    mHandler.sendEmptyMessage(1);
                }else{
//                  提示用户,请求失败
                }
            };
        }.start();
    }

    //展示dialog
    public void showwdialog(){
//      int code = getcode.getVersionCode(MainActivity.this);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("检查更新!");
        builder.setMessage("是否下载更新");
        builder.setPositiveButton("立即下载", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                showload();
            }
        }).setNegativeButton("以后再说", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.show();
    }


    public void showload(){
//      开始下载文件
        new Thread(){
            public void run() {
                Download.loadFile("http://gdown.baidu.com/data/wisegame/f98d235e39e29031/baiduxinwen.apk",mHandler);
            };
        }.start();

//      弹出是否进入后台下载框
        LinearLayout layout = (LinearLayout)LayoutInflater.from(MainActivity.this).inflate(R.layout.loaddialog,null);
        progressbar1 = (ProgressBar) layout.findViewById(R.id.progressbar1);
        Builder my_builder  = new Builder(MainActivity.this);
        my_builder.setView(layout);

        my_builder.setPositiveButton("后台下载", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        my_builder.show();
    }


    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){
            case 1:
                showwdialog();
                break;
            case 11:  
                // 正在下载   设置进度条位置   
                pregress_cont = msg.arg1;
                progressbar1.setProgress(pregress_cont);
                break;  
            case 200:  
//              通知安装下载的apk
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), "baiduxinwen.apk")),
                        "application/vnd.android.package-archive");
                MainActivity.this.startActivity(intent);
                break;  
            default:  
                break;  
            }  
        };  
    };
}

//我们看到在主类中我们使用到了检验版本号 那么如何知道我们的apk的版本号呢

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
public class GetVersionCode {
    public int getVersionCode(Context context) {
        int versionCode = 0;
        try{
            // 获取软件版本号,
            versionCode = context.getPackageManager().getPackageInfo(
                    "com.bawei.version_update", 0).versionCode;
        }catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
}

这样我们就获得了系统的版本号 我们在知道版本号更新的时候我们需要下载新的版本应用 也就是我们需要的链接网络的操作

import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class Httputils {
    //请求服务器
        public static String http_post(String url,List<NameValuePair> pair){
            String str = "";
            HttpPost httpRequest = new HttpPost(url);
            try {
                httpRequest.setEntity(new UrlEncodedFormEntity(pair,HTTP.UTF_8));
//              HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
                HttpResponse response = new DefaultHttpClient().execute(httpRequest);
                if(response.getStatusLine().getStatusCode()==200){
                    str = EntityUtils.toString(response.getEntity());
                    Log.i("TAG", "请求返回结果==="+str.toString());
                }else{
                    //请求失败返回值
                    str = "000";
                }
            } catch (Exception e) {
                e.printStackTrace();
                //请求失败返回值
                str = "000";
            } 
            return str;
        }
}

//下载文件的代码

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
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 android.os.Environment;
import android.os.Handler;
import android.os.Message;

public class Download {
    //下载文件
    public static void loadFile(String url,Handler mHandler) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse response;
        try {
            response = client.execute(get);

            HttpEntity entity = response.getEntity();
            float length = entity.getContentLength();

            InputStream is = entity.getContent();
            FileOutputStream fileOutputStream = null;
            if (is != null) {
                File file = new File(Environment.getExternalStorageDirectory(),
                        "baiduxinwen.apk");
                fileOutputStream = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                int ch = -1;
                float count = 0;
                while ((ch = is.read(buf)) != -1) {
                    fileOutputStream.write(buf, 0, ch);
                    count += ch;
//                  sendMsg(1,(int) (count*100/length));
                    //正在下载,计算下载大小
                    int pregress_cont = (int) (((float) count / length) * 100); 
                    Message mes = new Message();
                    mes.arg1 = pregress_cont;
                    mes.what= 11;
                    mHandler.sendMessage(mes);
                }
            }
            //下载完成,发送消息---通知安装
            mHandler.sendEmptyMessage(200);
            fileOutputStream.flush();
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (Exception e) {
//          sendMsg(-1,0);
        }
    }
}

当然了我们的布局不可能就是一个按钮 中间我们还有弹出框提示 提示我们下载应用的进度

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="6dp"
        android:layout_marginLeft="4dp"
        android:layout_marginTop="10dp"
        android:textColor="#000" />

    <ProgressBar
        android:id="@+id/progressbar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:max="100"
        android:progress="0" />
</LinearLayout>

最后千万不要忘记了配置权限

<uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" >
    </uses-permission> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
    </uses-permission>

这个时候我们运行一下就能看到一般的版本更新的流程了 就是这么实现的了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值