1.直接上代碼
package com.holl.vwifi.login.ui; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import cn.jpush.android.api.InstrumentedActivity; import com.holl.vwifi.R; import com.holl.vwifi.application.AppContext; import com.holl.vwifi.login.bean.ApkInfo; import com.holl.vwifi.login.bean.MyDevInfo; import com.holl.vwifi.login.bean.User; import com.holl.vwifi.login.common.CommandManagement; import com.holl.vwifi.login.db.DbManager; import com.holl.vwifi.login.task.DownLoadFileTask; import com.holl.vwifi.util.ComHelper; import com.holl.vwifi.util.Logger; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; 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.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.LinearLayout; import android.widget.Toast; /** * 應用程序啟動類:顯示歡迎界面並跳轉到主界面 * @Description: (這里用一句話描述這個類的作用) * @author yehj * @date 2014-8-7 上午9:28:15 * @version 1.01 */ public class AppStart extends InstrumentedActivity { private static final String TAG="AppStart"; private MyDevInfo devInfo; private ProgressDialog progressDialog ; private static final String SHAREDPREFERENCES_NAME = "first_pref"; private static final String transferIp="112.124.124.183"; private boolean isFirstIn ; private AppContext appContext;// 全局Context ApkInfo info=null; DownLoadFileThreadTask task; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); // 判斷服務器版本號 和客戶端的版本號 是否相同 if(msg.what==0){ //showUpdataDialog();//彈出來升級對話框 } if(msg.what==1){//下載 progressDialog.show(); new Thread(task).start(); } if(msg.what==2){//下載過程中,網絡異常 Toast.makeText(AppStart.this,R.string.download_apk_fail,Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } if(msg.what==3){//到導航頁面 } } }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); final View view = View.inflate(this, R.layout.start, null); LinearLayout wellcome = (LinearLayout) view.findViewById(R.id.app_start_view); setContentView(view); appContext = (AppContext) getApplication(); //漸變展示啟動屏 AlphaAnimation aa = new AlphaAnimation(0.3f,1.0f); aa.setDuration(2000); view.startAnimation(aa); aa.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation arg0) { redirectTo(); } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationStart(Animation animation) {} }); progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage(this.getResources().getText(R.string.downloading)); progressDialog.setCancelable(false);//注意一下 new Thread(){ @Override public void run() { try { sleep(1000); //handler.sendEmptyMessage(0); if (isNeedUpdate(getVerCode())) { //彈出來升級對話框 mHandler.sendEmptyMessage(0); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } /** * 跳轉到... */ private void redirectTo(){ SharedPreferences preferences = getSharedPreferences( SHAREDPREFERENCES_NAME, MODE_PRIVATE); // 取得相應的值,如果沒有該值,說明還未寫入,用true作為默認值 isFirstIn = preferences.getBoolean("isFirstIn", true); Intent intent=null; if(isFirstIn){ intent= new Intent(this, GuideActivity.class); startActivity(intent); }else{ Logger.d(TAG,appContext.ifHaveUserLogin()+"" ); if(appContext.ifHaveUserLogin()){ intent= new Intent(this, LoginBindRouter.class); startActivity(intent); }else{ if(ComHelper.isWifiConnected(appContext)){ appContext.getCom().connectVwifi(null, null, ComHelper.getGateWay(appContext), transferIp); int flag=appContext.getCom().connectvwifiready(); Logger.d("yehj","flag=="+flag); if(flag==0){ devInfo=appContext.getCom().getMyDevInfo(); if(devInfo!=null&&devInfo.getRes()!=null&&devInfo.getRes().equals("0")){ appContext.setWifiSSID(devInfo.getAp_Info().getSSID()); Logger.d("yehj", "STATUS=="+devInfo.getSTATUS()); if(devInfo.getSTATUS()!=null&&devInfo.getSTATUS().equals("0")){ intent=new Intent(this,CheckWanActivity.class); startActivity(intent); }else{ intent=new Intent(this,LoginBindRouter.class); startActivity(intent); } } }else{ intent=new Intent(this,LoginBindRouter.class); startActivity(intent); } }else{ intent=new Intent(this,LoginBindRouter.class); startActivity(intent); } } } finish(); } /** * * @param versiontext * 當前客戶端的版本號信息 * @return 是否需要更新 */ private boolean isNeedUpdate(int versionCode) { try { info =getUpdateApkInfo(); int latestCode = info.getVersionCode();//這里info可以為空,會跳到異常處理里面 if (latestCode<=versionCode) { //Log.i("splashActivity", "版本相同,無需升級, 進入主界面"); return false; } else { //Log.i("splashActivity", "版本不同,需要升級"); return true; } } catch (Exception e) { e.printStackTrace(); //Log.i("splashActivity", "獲取更新信息異常, 進入主界面"); return false; } } public int getVerCode() { int verCode = -1; try { verCode = this.getPackageManager().getPackageInfo("com.holl.vwifi", 0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } return verCode; } /** * 安裝apk * @param file */ private void install(File file){ Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); finish(); startActivity(intent); } //檢查版本更新 private ApkInfo getUpdateApkInfo(){ ApkInfo apkInfo=null; InputStream inputStream=null; HttpURLConnection connection=null; try { URL url=new URL("http://www.holl.cn/APP/android/holl_smart.xml"); connection= (HttpURLConnection)url.openConnection();// connection.setRequestMethod("GET"); connection.setConnectTimeout(2000);//設置連接主機超時(單位:毫秒) connection.setReadTimeout(2000);//設置從主機讀取數據超時(單位:毫秒) if(connection.getResponseCode()!= 200){ return apkInfo; } inputStream=connection.getInputStream(); XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance(); XmlPullParser parser = pullParserFactory.newPullParser(); parser.setInput(inputStream, "UTF-8"); // 編碼 int event = parser.getEventType();// 產生第一個事件 while (event!=parser.END_DOCUMENT) { switch (event) { case XmlPullParser.START_DOCUMENT: apkInfo = new ApkInfo(); break; case XmlPullParser.START_TAG:// 判斷當前事件是否是標簽元素開始事件 String tempParser=parser.getName(); if ("name".equalsIgnoreCase(tempParser)) // 判斷開始標簽元素是否是CMD_RES { apkInfo.setName(parser.nextText()); } // 開始解析XML else if("version".equalsIgnoreCase(tempParser)){ apkInfo.setVersion(parser.nextText()); } else if("versionCode".equalsIgnoreCase(tempParser)){ apkInfo.setVersionCode(Integer.parseInt(parser.nextText())); } else if("desc".equalsIgnoreCase(tempParser)){ apkInfo.setDes(parser.nextText()); } else if("url".equalsIgnoreCase(tempParser)){ apkInfo.setUrl(parser.nextText()); } case XmlPullParser.END_TAG: break; } event = parser.next();//進入下一個元素並觸發相應事件 } } catch (Exception e) { e.printStackTrace(); apkInfo=null; }finally { try { if(inputStream != null) inputStream.close(); if(connection!=null) connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return apkInfo; } /** * 升級的對話框 */ private void showUpdataDialog() { AlertDialog.Builder buider = new Builder(this); buider.setIcon(R.drawable.prompt); buider.setTitle("升級提醒"); buider.setMessage("匯爾微管家"+info.getVersion()+"發布了!\n"+"更新內容: "+info.getDes()); buider.setCancelable(false); // 讓用戶不能取消對話框 buider.setPositiveButton("馬上升級", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { //Log.i("splashActivity", "下載apk文件" + info.getUrl()); if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ task=new DownLoadFileThreadTask(info.getUrl(), "/sdcard/holl/holl_smart.apk"); mHandler.sendEmptyMessage(1); }else{ Toast.makeText(getApplicationContext(), "sd卡不可用",Toast.LENGTH_SHORT).show(); } } }); buider.setNegativeButton("以后再說", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { //Log.i("splashActivity", "用戶取消進入程序主界面") } }); buider.create().show(); } private class DownLoadFileThreadTask implements Runnable { private String path; // 服務器路徑 private String filepath; // 本地文件路徑 public DownLoadFileThreadTask(String path, String filepath) { this.path = path; this.filepath = filepath; } public void run() { try { File file = DownLoadFileTask.getFile(path, filepath,progressDialog); //Log.i("splashActivity","下載成功"); progressDialog.dismiss(); install(file); } catch (Exception e) { e.printStackTrace(); mHandler.sendEmptyMessage(2);//"下載fail" } } } }
布局文件很簡單
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/app_start_view" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="bottom" android:background="@drawable/start_background"> </LinearLayout>