版本更新

版本更行之前先有個動畫

package com.bwie.test;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化控件
        ImageView img = (ImageView) findViewById(R.id.img);
        //設置動畫
        RotateAnimation  animation = new RotateAnimation(0, 360*4, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        //設置動畫時間
        animation.setDuration(2000);
        //保持動畫結束時候的狀態、
        animation.setFillAfter(true);
        img.setAnimation(animation);
        //設置動畫的監聽事件
        animation.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // TODO Auto-generated method stub
                Intent  in = new Intent(MainActivity.this, Main2Activity.class);
    is, Main2Activity.class);
            startActivity(in);
            }
        });
    }

}


package com.bwie.test;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class Main2Activity extends ActionBarActivity {

    private int versionCode;
    private String path = "http://www.oschina.net/MobileAppVersion.xml";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        // 獲得當前版本號
        try {
            versionCode = getVersionName();
            Log.e("TAG", "項目版本號:" + versionCode);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 請求網絡數據
        forInfo();
    }

    // 請求網絡數據
    private void forInfo() {
        new AsyncTask<String, Void, InputStream>() {

            @Override
            protected InputStream doInBackground(String... params) {
                try {
                    URL url = new URL(path);

                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();

                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(3000);

                    // /判斷結果碼
                    if (conn.getResponseCode() == 200) {
                        InputStream inputStream = conn.getInputStream();

                        return inputStream;
                    }

                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(InputStream result) {
                super.onPostExecute(result);
                // 解析xml文件
                try {
                    UpdataInfo info = getUpdataInfo(result);
                   Log.e("TAG", "info.vercode= "+info.versionCode);
                    // 對比版本號
                    if (info.versionCode.equals(versionCode+"")) {
                        Toast.makeText(Main2Activity.this, "已經是最新版本",
                                Toast.LENGTH_SHORT).show();
                    } else {

                        // 彈出提示框
                        tishigengxin(info);
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        }.execute(path);

    }

    // 提示更新的框
    protected void tishigengxin(final UpdataInfo info) {
        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle("有新版本").setMessage(info.updateLog);

        builder.setNegativeButton("以後再說",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                    }
                });
        builder.setPositiveButton("立即更新",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        xiazaiapk(info.downloadUrl);// 下載
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();

    }

    // 下載APK
    protected void xiazaiapk(final String url) {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setTitle("正在下載新版本");
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.show();

        new Thread() {
            public void run() {
                File file = getapk(pd, url);
                try {
                    sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(file),
                        "application/vnd.android.package-archive");
                startActivity(intent);
                pd.dismiss();
            }
        }.start();

    }

    // 安裝APK
    protected File getapk(final ProgressDialog pd, final String url) {

        try {
            URL url2 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
            conn.setConnectTimeout(5000);
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                int contentLength = conn.getContentLength();
                pd.setMax(contentLength);
                InputStream inputStream = conn.getInputStream();
                File file = new File(Environment.getExternalStorageDirectory(),
                        "update.apk");
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                int len = 0;
                byte[] buffer = new byte[1024];
                int total = 0;
                while ((len = bis.read(buffer)) != -1) {

                    fileOutputStream.write(buffer, 0, len);
                    total += len;
                    pd.setProgress(total);
                }

                return file;
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    // 獲得當前版本號
    private int getVersionName() throws Exception {
        PackageManager packageManager = getPackageManager();
        PackageInfo packageInfo = packageManager.getPackageInfo(
                "com.bwie.test", 0);
        return packageInfo.versionCode;
    }

    // 獲得服務器的版本號
    public static UpdataInfo getUpdataInfo(InputStream is) throws Exception {
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(is, "utf-8");// 設置解析的數據源
        int type = parser.getEventType();
        UpdataInfo info = new UpdataInfo();// 實體
        while (type != XmlPullParser.END_DOCUMENT) {
            switch (type) {
            case XmlPullParser.START_TAG:
                if ("versionCode".equals(parser.getName())) {
                    info.versionCode = parser.nextText(); // 獲取版本號
                } else if ("downloadUrl".equals(parser.getName())) {
                    info.downloadUrl = parser.nextText(); // 獲取要升級的APK文件
                } else if ("updateLog".equals(parser.getName())) {
                    info.updateLog = parser.nextText(); // 獲取該文件的信息
                }
                break;
            }
            type = parser.next();
        }
        return info;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章