版本更新(自开服务器版)

来源:互联网 发布:环保75标准数据 编辑:程序博客网 时间:2024/06/06 03:46

一:版本更新有两种方式,可以是请求网上的数据,也可以是自开服务器,本文介绍的是自开服务器版。

二:首先下载tomcat服务器,workapps目录下有一个ROOT目录,在他下面你建一个文件夹,里面放两个东西一个是你等会请求的文件(里面是你的ip,resoncode),一个是你要更新的apk。返回到bin目录下点击startup.bat点击然后别管他让他在后台运行着,这样服务器就相当于开着呢。

三:接下来就是java代码了

     1:封装bean包,里面是你请求的属性版本号,相关提醒,路径等。

    public String version;

    public String url;

   public String description;

    2:设置TAG

public class Conf {
    public static final String TAG = "Baidu Mobstat";
}
    3:接下来是xml解析pull解析类

        public class UpdateTools {

    public static UpdateEntity getUpdataInfo(InputStream is) throws Exception {
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(is, "utf-8");
        int type = parser.getEventType();
        UpdateEntity info = new UpdateEntity();
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
                case XmlPullParser.START_TAG:
                    if ("version".equals(parser.getName())) {
                        info.setVersion(parser.nextText());
                    } else if ("url".equals(parser.getName())) {
                        info.setUrl(parser.nextText());
                    } else if ("description".equals(parser.getName())) {
                        info.setDescription(parser.nextText());
                    }
                    break;
            }
            type = parser.next();
        }
        return info;
    }
    public void installApk(File file,Context context) {
        Intent intent = new Intent();
    
        intent.setAction(Intent.ACTION_VIEW);
      
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
4:最后是在main类里面写代码了

public class MainActivity extends Activity {

    private AlertDialog dialog;

    private UpdateEntity updateEntity;

    private TextView tv_name;
 
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);

            switch (msg.what) {
                case 0:
                    dialog.setMessage(updateEntity.getDescription());
                    dialog.show();
                    break;

                case 1:
                    downLoadApk();
                    break;
            }


        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dialog = new AlertDialog.Builder(MainActivity.this).
                setTitle("版本升级").
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("本次升级", onclick).
                setNegativeButton("下次升级", null).
                create();



      
        new Thread(new CheckVersionTask()).start();
    }

    DialogInterface.OnClickListener  onclick = new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            handler.sendEmptyMessage(1);
        }

    };


    protected void downLoadApk() {
        final ProgressDialog pd;    //杩涘害鏉″璇濇
        pd = new  ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("姝e湪涓嬭浇鏇存柊");
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    File file =  getFileFromServer(updateEntity.getUrl(), pd);
                    sleep(3000);

                    UpdateTools tools = new UpdateTools();
               
                    tools.installApk(file,MainActivity.this);
                    pd.dismiss();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }}.start();
    }

   
    public class CheckVersionTask implements Runnable{

        public void run() {
            try {
                String path = getResources().getString(R.string.serverurl);
             
                URL url = new URL(path);
                HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                InputStream is =conn.getInputStream();
                updateEntity =  UpdateTools.getUpdataInfo(is);

                int versionCode = MainActivity.this.getPackageManager().getPackageInfo(MainActivity.this.getPackageName(), 0).versionCode;

                if(Integer.parseInt(updateEntity.getVersion()) <= versionCode){
                    Log.i("xxx","haha");
                }else{
                    Log.i("xxxx","heihei ");
                    handler.sendEmptyMessage(0);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public File getFileFromServer(String path, ProgressDialog pd)
            throws Exception {

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
       
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(),
                    "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
        
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    @Override
    protected void onPause() {
        Log.w(Conf.TAG, "Activity1.onPause()");
        // TODO Auto-generated method stub
        super.onPause();

    }

    @Override
    protected void onResume() {
        Log.w(Conf.TAG, "Activity1.onResume()");
        // TODO Auto-generated method stub
        super.onResume();

    }


}



0 0