Android下載並安裝APK
阿新 • • 發佈:2019-01-27
package com.cardvalue.sys.activitys; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; import java.util.Map; import java.util.Set; import android.annotation.SuppressLint; import android.app.DownloadManager; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import cn.jpush.android.api.InstrumentedActivity; import cn.jpush.android.api.JPushInterface; import cn.jpush.android.api.TagAliasCallback; import com.cardvlaue.sys.R; import com.cardvalue.sys.annotation.EControl; import com.cardvalue.sys.annotation.EventType; import com.cardvalue.sys.annotation.FCallHandler; import com.cardvalue.sys.annotation.FControl; import com.cardvalue.sys.common.CMessage; import com.cardvalue.sys.common.MD5Util; import com.cardvalue.sys.common.MessageBox; import com.cardvalue.sys.common.MyApplication; import com.cardvalue.sys.newnetwork.BusinessServices; import com.cardvalue.sys.newnetwork.Config; import com.cardvalue.sys.newnetwork.Convert; import com.cardvalue.sys.newnetwork.CustomHandler; import com.cardvalue.sys.newnetwork.UserServices; import com.cardvalue.sys.newnetwork.Utiltools; import com.cardvalue.sys.widget.WelcomeDialog; import com.cardvalue.sys.widget.WelcomeDialog.onAttendOrNotListener; import com.cardvalue.sys.widget.WelcomeDialog.onCancelListener; //import com.tencent.stat.StatService; /** * 歡迎頁面 */ public class WelcomeActivity extends InstrumentedActivity { private Map<String, Object> active = null; // 活動頁的相關資訊 private Map<String, Object> showIcon = null; // 首頁顯示的圖示 public CustomHandler handler; public ProgressDialog dialog; public UserServices userService = new UserServices(); public BusinessServices businessService = new BusinessServices(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.welcome); // StatService.trackCustomEvent(this, "onCreate", ""); EControl control = new EControl(this); control.setOnClickLisenner(clickLinstenner); // 設定所有的點選事件 control.InitControl(); // 開始初始化控制元件 handler = new CustomHandler(this); // 初始化handler dialog = new ProgressDialog(this); JPushInterface.init(getApplicationContext()); Utiltools.printE("Jpush data=========>" + JPushInterface.getRegistrationID(this)); handler.sendMessage(handler.obtainMessage(MSG_SET_ALIAS, "android")); userService.setValue(this, handler, CMessage.NET_MSG_GETNEWVERSION); if (hasNetworkAvailable()) { userService.getVersionInformation(); } else { MessageBox.ToastShow("沒有可用網路連線,請檢查你的網路!", WelcomeActivity.this); // 沒有網路的時候直接到home頁 handler.sendEmptyMessageDelayed(NORMAL_MSG_HOME, 3000); } } /*********************************************************************************************************************************************** * 定義控制元件,並指定控制元件對應的ID ***********************************************************************************************************************************************/ @FControl(id = R.id.imageView1) public ImageView bg1; // 第一張背景圖 @FControl(id = R.id.imageView2, eventType = EventType.ON_CLICK) public ImageView bg2; // 第二張背景圖 @FControl(id = R.id.btn, eventType = EventType.ON_CLICK) public Button button; // 跳過按鈕 @FControl(id = R.id.ry_wecome) public RelativeLayout wLayout; // 第二張背景圖及按鈕的佈局 /********************************************************************************************************************************************* * 處理所有的onclick事件 *********************************************************************************************************************************************/ public OnClickListener clickLinstenner = new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.imageView2: // 按下了活動圖片後觸發 String isForward = (String) active.get("forwardType"); // 判斷是否跳轉 if (isForward.equals("1")) { handler.removeMessages(NORMAL_MSG_LOGIN); Intent intent = new Intent(WelcomeActivity.this, LoadWebPage.class); intent.putExtra("title", "活動規則"); intent.putExtra("welcome", "welcome"); intent.putExtra("url", (String) active.get("forwordUrl")); startActivity(intent); WelcomeActivity.this.finish(); } break; case R.id.btn: // 按下了跳過按鈕 handler.removeMessages(NORMAL_MSG_LOGIN); startActivity(new Intent(WelcomeActivity.this, Home.class)); WelcomeActivity.this.finish(); break; } } }; /** * 獲取最新的伺服器版本資訊 */ @SuppressWarnings("unchecked") @FCallHandler(id = CMessage.NET_MSG_GETNEWVERSION) public void getNewVersion() { handler.tempMap = (Map<String, Object>) handler.resultMap .get("resultData"); int clientCode = Utiltools.getAppVersionCode(this); // 客戶端的版本code int serverCode = Integer.parseInt(handler.tempMap.get("versionCode") .toString()); // 服務端的版本code final String isForceUpdate = handler.tempMap.get("isForceUpdate") .toString(); // 是否強制更新 0不強制更新(可以選擇) 1:必須更新 active = (Map<String, Object>) handler.tempMap.get("welecomeSet"); Utiltools.printE("handler.tempMap" + "=====" + handler.tempMap); Utiltools.printE("Convert.convertMap(active).size()" + "=====" + Convert.convertMap(active).size()); if (Convert.convertMap(active).size() != 0) { // http://www.cvbaoli.com/webak/resources/newm/images/welcome/welcome640-1136.png String imgUrl = Config.getWeixinIp() + "resources/image/welcome/" + (String) active.get("picName") + "640-1136." + (String) active.get("suffix"); Utiltools.loadPic(this, imgUrl, bg2, R.drawable.welcome2, R.drawable.welcome2); // 載入網路圖片 Utiltools.printE("imgUrlimgUrl"); } else { Utiltools.loadPic(this, "", bg2, R.drawable.welcome2, R.drawable.welcome2); Utiltools.printE("imgUrlimgUrl" + "===4444==="); } // msg 中的內容根據是否強制更新的不同而進行改變 String msg = isForceUpdate.equals("0") ? Utiltools .getString(R.string.updateSystem) : Utiltools .getString(R.string.needUpdateSystem); final WelcomeDialog mwelComeDialog = new WelcomeDialog( WelcomeActivity.this, msg); if (serverCode > clientCode) {// 伺服器大於本地 就要更新 onAttendOrNotListener welCome = new onAttendOrNotListener() { @SuppressLint("NewApi") @Override public void AttendOrNot() { MessageBox.show(dialog, "", "正在下載最新版本,請稍後..."); String url = handler.tempMap.get("url").toString(); DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request( Uri.parse(url)); request.setDestinationInExternalPublicDir("/cardvalue", "cardvalue.apk"); request.setVisibleInDownloadsUi(true); request.setTitle("卡得萬利"); downloadManager.enqueue(request); } }; onCancelListener onCancel = new onCancelListener() { @Override public void Cancel() { if (isForceUpdate.equals("1")) { mwelComeDialog.cancel(); WelcomeActivity.this.finish(); } else { handler.sendEmptyMessage(NORMAL_MSG_START); mwelComeDialog.cancel(); } } }; mwelComeDialog.setOnAttendOrNotListener(welCome); mwelComeDialog.setCancelListener(onCancel); mwelComeDialog.show(); } else { handler.sendEmptyMessage(NORMAL_MSG_START); } } /** * 開始正常的流程 */ @FCallHandler(id = NORMAL_MSG_START) public void startProcess() { Utiltools.printE("開始正常的流程=====" + Convert.convertMap(active).size()); if (Convert.convertMap(active).size() == 0) { handler.sendEmptyMessageDelayed(NORMAL_MSG_LOGIN, 3000); // 5秒以後進入登入頁 return; } bg1.setVisibility(View.GONE); // 設定背景1層消失 wLayout.setVisibility(View.VISIBLE); // 設定背景層顯示 bg2.setVisibility(View.VISIBLE); // 設定背景2層的圖片顯示 button.setVisibility(View.VISIBLE); // 設定背景2層的按鈕顯示 handler.sendEmptyMessageDelayed(NORMAL_MSG_LOGIN, 5000); // 5秒以後進入登入頁 } @FCallHandler(id = NORMAL_MSG_HOME) public void home() { startActivity(new Intent(WelcomeActivity.this, Home.class)); WelcomeActivity.this.finish(); } /** * 開始登陸操作 */ @FCallHandler(id = NORMAL_MSG_LOGIN) public void login() { Utiltools.printE("LOGIN====LOGIN"); String username = MyApplication.getApplication().getLocalCache() .getString("username"); // 獲取使用者名稱 String password = MyApplication.getApplication().getLocalCache() .getString("password"); // 獲取密碼 if (username.equals("") || password.equals("")) { startActivity(new Intent(WelcomeActivity.this, Home.class)); WelcomeActivity.this.finish(); return; } String pushId = JPushInterface.getRegistrationID(this); long data = System.currentTimeMillis() / 1000; String pass1 = MD5Util.MD5(MD5Util.MD5(password) + "cvbaoli" + data) + "|" + data; try { userService.setValue(WelcomeActivity.this, handler, CMessage.NET_MSG_LOGIN); userService.login(username, URLEncoder.encode(pass1, "utf8"), "mj_"+pushId, null); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * 登陸成功後的操作 */ @FCallHandler(id = CMessage.NET_MSG_LOGIN) public void loginSuccess() { dialog.cancel(); MyApplication.getApplication().setLogin(true); MyApplication.getApplication().getLocalCache() .putString("exirDate", String.valueOf(new Date().getTime())); startActivity(new Intent(WelcomeActivity.this, Home.class)); WelcomeActivity.this.finish(); } /** * 下載完成後廣播接收類 */ class DownloadCompleteReceiver extends BroadcastReceiver { @SuppressLint("NewApi") @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) { DownloadManager downloadManager = (DownloadManager) context .getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Query query = new DownloadManager.Query(); query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL); Cursor c = downloadManager.query(query); // 獲取檔名並開始安裝 if (c.moveToFirst()) { String fileName = c.getString(c .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); fileName = fileName.replace("file://", ""); File file = new File(fileName); Utiltools.print("weiweina", "file = " + fileName); Intent intent1 = new Intent(Intent.ACTION_VIEW); intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent1.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startActivity(intent1); WelcomeActivity.this.finish(); } } } } // 註冊廣播 public DownloadCompleteReceiver receiver = new DownloadCompleteReceiver(); @Override protected void onResume() { registerReceiver(receiver, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE)); super.onResume(); } @Override protected void onDestroy() { if (receiver != null) unregisterReceiver(receiver); super.onDestroy(); } /**************************************************************************************************************************************** * 自定義訊息 ****************************************************************************************************************************************/ private static final int NORMAL_MSG_START = 1; // 進入正常流程訊息 public static final int NORMAL_MSG_LOGIN = 2; // 開始進行登陸操作 public static final int NORMAL_MSG_HOME = 3; // 延遲3秒到首頁 public static final int MSG_SET_ALIAS = 10001; public static final String MESSAGE_RECEIVED_ACTION = "com.cardvlaue.sys.MESSAGE_RECEIVED_ACTION"; public static final String KEY_TITLE = "title"; public static final String KEY_MESSAGE = "message"; public static final String KEY_EXTRAS = "extras"; private final TagAliasCallback mAliasCallback = new TagAliasCallback() { @Override public void gotResult(int code, String alias, Set<String> tags) { switch (code) { case 6002: if (isConnected(getApplicationContext())) { handler.sendMessageDelayed( handler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60); } break; } } }; public static boolean isConnected(Context context) { ConnectivityManager conn = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = conn.getActiveNetworkInfo(); return (info != null && info.isConnected()); } @FCallHandler(id = MSG_SET_ALIAS) public void setAlias() { Utiltools.print("極光呼叫了......................"); JPushInterface.setAliasAndTags(getApplicationContext(), (String) handler.msg.obj, null, mAliasCallback); } /** * 判斷網路是否連線 */ private boolean hasNetworkAvailable() { ConnectivityManager cm = (ConnectivityManager) this .getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) { return false; } else { NetworkInfo[] info = cm.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } }