android 版本更新
来源:互联网 发布:编程入门教学视频 编辑:程序博客网 时间:2024/06/07 16:12
//更新的类
public class GetNewVerson { private Request<String> request; private MyApplication myApplication; private Context context; public GetNewVerson(Context context) { this.context = context; myApplication = (MyApplication) context.getApplicationContext(); }//网络请求 public void getNewVerson(){ // 创建请求对象。 request = NoHttp.createStringRequest(SysConfig.SERVER_HOST_ADDRESS + "/sys/getSystemUpdate", RequestMethod.GET); //设置为必须网络 request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK); Map<String, String> paramMap = new HashMap<String, String>(); //增加请求参数及数值 if (request != null) { paramMap.put("versionType", "1");// String类型 // 添加到请求队列 DataUtil.requestDateContrl(paramMap, request); CallServer.getRequestInstance().add(context, 2, request, httpListener, true, false); } } /** * 请求返回 */ private HttpListener<String> httpListener; private SystemUpdate systemUpdate; { httpListener = new HttpListener<String>() { @Override public void onSucceed(int what, Response<String> response) { int responseCode = response.getHeaders().getResponseCode();// 服务器响应码 if (responseCode == 200) { if (RequestMethod.HEAD == response.getRequestMethod()) { // 请求方法为HEAD时没有响应内容// showMessageDialog(R.string.request_succeed, R.string.request_method_head); } else { JSONObject jsonResult = null; try { jsonResult = new JSONObject(response.get()); } catch (JSONException e) { e.printStackTrace(); } switch (what) { case 2://请求 try { // 如果成功 if (jsonResult != null && jsonResult.getString("code").equals(SysConfig.ERROR_CODE_SUCCESS)) { //请求返回的bean SystemUpdateBean systemUpdateBean = GsonControl.getPerson(jsonResult.getString("data"), SystemUpdateBean.class); systemUpdate = systemUpdateBean.getSystemUpdate(); if (systemUpdate != null && systemUpdate.getVersionInt() != null && !"".equals(systemUpdate .getVersionInt())) { if (getAppVersionName() < Integer .parseInt(systemUpdate .getVersionInt())) { final String downloadUrl = systemUpdate .getUpdateUrl(); // 更新提示 final MyAlertDialog dialog = new MyAlertDialog( context) .builder("0.85") .setMsg("发现新版本,建议您立即更新!") .setNegativeButton( "下次再说", new View.OnClickListener() { @Override public void onClick( View v) { // do // nothing } }); dialog.setPositiveButton("立即更新", new View.OnClickListener() { @Override public void onClick( View v) { sysNotice("开始下载");
//下载的服务 Intent intent = new Intent( context, UpdateService.class); intent.putExtra( "url", downloadUrl); context.startService(intent); } }); dialog.setCancelable(true); dialog.show(); } else { } } else { } } else {// 不成功 if (!DataUtil.isEmpty(jsonResult.getString("onceToken")) && !"null".equals(jsonResult.getString("onceToken"))) { myApplication.setOnceToken(jsonResult.getString("onceToken")); } return; } } catch (Exception e) { e.printStackTrace(); } break; default: break; } } } } @Override public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) { switch (what) { case 0: break; } } }; } /** * 显示消息 */ public void sysNotice(String message) { MyToast.getToast(context).systemNotice(message); } /** * 获取当前版本号 */ private int getAppVersionName() { int versionName = 0; try { PackageManager packageManager = context.getPackageManager(); PackageInfo packageInfo = packageManager.getPackageInfo( context.getPackageName(), 0); versionName = packageInfo.versionCode; } catch (Exception e) { e.printStackTrace(); } return versionName; }}
//下载的服务(不要忘了在Mainfest中注册)
//还要引用//httpclientcompile files('libs/httpclient-4.3.5.jar')compile files('libs/httpcore-4.3.2.jar')compile files('libs/httpmime-4.3.5.jar')
public class UpdateService extends Service { private NotificationManager nm; // private Notification notification; private File tempFile = null; private boolean cancelUpdate = false; private MyHandler myHandler; private int download_precent = 0; private RemoteViews views; private int notificationId = 1234; private Notification.Builder builder; @Override public IBinder onBind(Intent intent) { return null; } @SuppressWarnings("deprecation") @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } @SuppressWarnings("deprecation") @Override public int onStartCommand(Intent intent, int flags, int startId) { nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// notification=new Notification();// notification.icon=android.R.drawable.stat_sys_download;// notification.tickerText=getString(R.string.app_name)+"更新";// notification.when=System.currentTimeMillis();// notification.defaults=Notification.DEFAULT_LIGHTS; //设置任务栏中下载进程显示的views views = new RemoteViews(getPackageName(), R.layout.ly_update);// notification.contentView=views; PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);// notification.setLatestEventInfo(this, "", "", contentIntent); builder = new Notification.Builder(this) .setAutoCancel(true) .setContentTitle(getString(R.string.app_name) + "更新") .setContentText("describe") .setContentIntent(contentIntent) .setSmallIcon(android.R.drawable.stat_sys_download) .setWhen(System.currentTimeMillis()) .setDefaults(Notification.DEFAULT_LIGHTS) .setContent(views) ; //将下载任务添加到任务栏中 nm.notify(notificationId, builder.getNotification()); myHandler = new MyHandler(Looper.myLooper(), this); //初始化下载任务内容views Message message = myHandler.obtainMessage(3, 0); myHandler.sendMessage(message); //启动线程开始执行下载任务 downFile(intent.getStringExtra("url")); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); } //下载更新文件 private void downFile(final String url) { new Thread() { public void run() { try { HttpClient client = new DefaultHttpClient(); // params[0]代表连接的url HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); long length = entity.getContentLength(); InputStream is = entity.getContent(); if (is != null) { File rootFile = new File(Environment.getExternalStorageDirectory().getPath(), "/pinke"); if (!rootFile.exists() && !rootFile.isDirectory()) rootFile.mkdir(); tempFile = new File(Environment.getExternalStorageDirectory().getPath(), "/pinke/" + url.substring(url.lastIndexOf("/") + 1)); if (tempFile.exists()) tempFile.delete(); tempFile.createNewFile(); //已读出流作为参数创建一个带有缓冲的输出流 BufferedInputStream bis = new BufferedInputStream(is); //创建一个新的写入流,讲读取到的图像数据写入到文件中 FileOutputStream fos = new FileOutputStream(tempFile); //已写入流作为参数创建一个带有缓冲的写入流 BufferedOutputStream bos = new BufferedOutputStream(fos); int read; long count = 0; int precent = 0; byte[] buffer = new byte[1024]; while ((read = bis.read(buffer)) != -1 && !cancelUpdate) { bos.write(buffer, 0, read); count += read; precent = (int) (((double) count / length) * 100); //每下载完成5%就通知任务栏进行修改下载进度 if (precent - download_precent >= 3) { download_precent = precent; Message message = myHandler.obtainMessage(3, precent); myHandler.sendMessage(message); } } bos.flush(); bos.close(); fos.flush(); fos.close(); is.close(); bis.close(); } if (!cancelUpdate) { Message message = myHandler.obtainMessage(2, tempFile); myHandler.sendMessage(message); } else { tempFile.delete(); } } catch (ClientProtocolException e) { Message message = myHandler.obtainMessage(4, "下载更新文件失败"); myHandler.sendMessage(message); } catch (IOException e) { Message message = myHandler.obtainMessage(4, "下载更新文件失败"); myHandler.sendMessage(message); } catch (Exception e) { Message message = myHandler.obtainMessage(4, "下载更新文件失败"); myHandler.sendMessage(message); } } }.start(); } //安装下载后的apk文件 private void Instanll(File file, Context context) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); context.startActivity(intent); } /*事件处理类*/ class MyHandler extends Handler { private Context context; public MyHandler(Looper looper, Context c) { super(looper); this.context = c; } @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg != null) { switch (msg.what) { case 0: Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show(); break; case 1: break; case 2: //下载完成后清除所有下载信息,执行安装提示 download_precent = 0; nm.cancel(notificationId); Instanll((File) msg.obj, context); //停止掉当前的服务 stopSelf(); break; case 3: //更新状态栏上的下载进度信息 views.setTextViewText(R.id.tvProcess, "已下载" + download_precent + "%"); views.setProgressBar(R.id.pbDownload, 100, download_precent, false);// notification.contentView=views; builder.setContent(views); nm.notify(notificationId, builder.getNotification()); break; case 4: nm.cancel(notificationId); break; } } } }}
//提示的dialog
public class MyAlertDialog { private Context context; private MyDialog dialog; private LinearLayout lLayout_bg; private TextView txt_title; private TextView txt_msg;// private EditText edittxt_result; private LinearLayout dialog_Group;// private ImageView dialog_marBottom; private Button btn_neg; private Button btn_pos;// private View img_line; private Display display; private boolean showTitle = false; private boolean showMsg = false; private boolean showEditText = false; private boolean showLayout = false; private boolean showPosBtn = false; private boolean showNegBtn = false; private View title_bottom_line; public MyAlertDialog(Context context) { this.context = context; WindowManager windowManager = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); display = windowManager.getDefaultDisplay(); } @SuppressWarnings("deprecation") @SuppressLint("InflateParams") public MyAlertDialog builder(String widthPercent) { // 获取Dialog布局 View view = LayoutInflater.from(context).inflate( R.layout.toast_view_alertdialog, null); // 获取自定义Dialog布局中的控件 lLayout_bg = (LinearLayout) view.findViewById(R.id.lLayout_bg); txt_title = (TextView) view.findViewById(R.id.txt_title); txt_title.setVisibility(View.GONE); txt_msg = (TextView) view.findViewById(R.id.txt_msg); txt_msg.setVisibility(View.GONE);// edittxt_result = (EditText) view.findViewById(R.id.edittxt_result);// edittxt_result.setVisibility(View.GONE); dialog_Group = (LinearLayout) view.findViewById(R.id.dialog_Group); dialog_Group.setVisibility(View.GONE);// dialog_marBottom = (ImageView) view.findViewById(R.id.dialog_marBottom); btn_neg = (Button) view.findViewById(R.id.btn_neg); btn_neg.setVisibility(View.GONE); btn_pos = (Button) view.findViewById(R.id.btn_pos); btn_pos.setVisibility(View.GONE);// img_line = (View) view.findViewById(R.id.img_line);// img_line.setVisibility(View.GONE); title_bottom_line = view.findViewById(R.id.title_bottom_line); // 定义Dialog布局和参数 dialog = new MyDialog(context, R.style.AlertDialogStyle); dialog.setContentView(view); // 调整dialog背景大小 if (widthPercent != null && widthPercent != "") { lLayout_bg.setLayoutParams(new FrameLayout.LayoutParams((int) (display .getWidth() * Double.parseDouble(widthPercent)), LayoutParams.WRAP_CONTENT)); } else { lLayout_bg.setLayoutParams(new FrameLayout.LayoutParams((int) (display .getWidth() * 0.85), LayoutParams.WRAP_CONTENT)); } return this; } public void showTitleBottomLine() { title_bottom_line.setVisibility(View.VISIBLE); } public MyAlertDialog setTitle(String title) { showTitle = true; if ("".equals(title)) { txt_title.setText("标题"); } else { txt_title.setText(title); } return this; } public MyAlertDialog setEditText(String msg) { showEditText = true; if ("".equals(msg)) {// edittxt_result.setHint("内容"); } else {// edittxt_result.setText(msg); } return this; } public String getResult() {// return edittxt_result.getText().toString(); return ""; } public MyAlertDialog setMsg(String msg) { showMsg = true; if ("".equals(msg)) { txt_msg.setText("内容"); } else { txt_msg.setText(msg); } return this; } public MyAlertDialog setView(View view) { showLayout = true; if (view == null) { showLayout = false; } else dialog_Group.addView(view, android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT); return this; } public MyAlertDialog setCancelable(boolean cancel) { dialog.setCancelable(cancel); return this; } public MyAlertDialog setPositiveButton(String text, final OnClickListener listener) { showPosBtn = true; if ("".equals(text)) { btn_pos.setText("确定"); } else { btn_pos.setText(text); } btn_pos.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listener.onClick(v); dialog.dismiss(); } }); return this; } public MyAlertDialog setPositiveButton(String text, final OnClickListener listener, final boolean dismissAble) { showPosBtn = true; if ("".equals(text)) { btn_pos.setText("确定"); } else { btn_pos.setText(text); } btn_pos.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listener.onClick(v); if (dismissAble) dialog.dismiss(); } }); return this; } public MyAlertDialog setNegativeButton(String text, final OnClickListener listener) { showNegBtn = true; if ("".equals(text)) { btn_neg.setText("取消"); } else { btn_neg.setText(text); } btn_neg.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listener.onClick(v); dialog.dismiss(); } }); return this; } public MyAlertDialog setNegativeButton(String text, final OnClickListener listener, final boolean dimissAble) { showNegBtn = true; if ("".equals(text)) { btn_neg.setText("取消"); } else { btn_neg.setText(text); } btn_neg.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listener.onClick(v); if (dimissAble) dialog.dismiss(); } }); return this; } public void dismiss() { dialog.dismiss(); } private void setLayout() {// if (!showTitle && !showMsg) {// txt_title.setText("提示");// txt_title.setVisibility(View.VISIBLE);// } if (showTitle) { txt_title.setVisibility(View.VISIBLE); } if (showEditText) {// edittxt_result.setVisibility(View.VISIBLE); } if (showMsg) { txt_msg.setVisibility(View.VISIBLE); } if (showLayout) { dialog_Group.setVisibility(View.VISIBLE);// dialog_marBottom.setVisibility(View.GONE); } if (!showPosBtn && !showNegBtn) { btn_pos.setText("确定"); btn_pos.setVisibility(View.VISIBLE); btn_pos.setBackgroundResource(R.drawable.sel_dialog_confirm); btn_pos.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); } if (showPosBtn && showNegBtn) { btn_pos.setVisibility(View.VISIBLE); btn_pos.setBackgroundResource(R.drawable.sel_dialog_confirm); btn_neg.setVisibility(View.VISIBLE); btn_neg.setBackgroundResource(R.drawable.sel_dialog_confirm);// img_line.setVisibility(View.VISIBLE); } if (showPosBtn && !showNegBtn) { btn_pos.setVisibility(View.VISIBLE); btn_pos.setBackgroundResource(R.drawable.sel_dialog_confirm); } if (!showPosBtn && showNegBtn) { btn_neg.setVisibility(View.VISIBLE); btn_neg.setBackgroundResource(R.drawable.sel_dialog_confirm); } } public void show() { setLayout(); dialog.show(); }}
//布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/lLayout_bg" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bg_dilog" android:orientation="vertical" > <TextView android:id="@+id/txt_title" android:layout_width="match_parent" android:layout_height="50dp" android:gravity="center" android:textColor="#ff4242" android:textSize="20sp" android:textStyle="normal" /> <View android:id="@+id/title_bottom_line" android:layout_width="match_parent" android:layout_height="1dp" android:background="#e0e0e0" android:visibility="gone" /> <TextView android:id="@+id/txt_msg" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="20dp" android:layout_marginBottom="20dp" android:gravity="left" android:textColor="@color/text_title" android:textSize="16sp" /> <LinearLayout android:id="@+id/dialog_Group" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:orientation="vertical" > </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <View android:id="@+id/imgh_line" android:layout_width="match_parent" android:layout_height="1dp" android:background="#e0e0e0" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/btn_neg" android:layout_width="wrap_content" android:layout_height="43dp" android:layout_weight="1" android:background="@drawable/sel_dialog_confirm" android:gravity="center" android:textColor="@color/cl_maintouch_tabs" android:textSize="16sp" /> <View android:id="@+id/img_line" android:layout_width="1dp" android:layout_height="43dp" android:background="#e0e0e0" /> <Button android:id="@+id/btn_pos" android:layout_width="wrap_content" android:layout_height="43dp" android:layout_weight="1" android:background="@drawable/sel_dialog_confirm" android:gravity="center" android:textColor="#fa625f" android:textSize="16sp" android:textStyle="normal" /> </LinearLayout></LinearLayout>
0 0
- Android版本更新
- Android SDK版本更新
- Android软件版本更新
- Android 检测版本更新
- Android之版本更新
- Android版本更新实现
- android版本更新问题
- android apk版本更新
- android版本更新
- Android 版本的更新
- Android版本更新
- Android提示版本更新
- android 版本更新
- Android应用版本更新
- android版本更新
- Android检测版本更新
- Android中版本更新
- Android 更新升级版本
- Bind event to element using pure Javascript
- iOS 常用宏
- 外观模式
- 关于xtk.js的使用(医疗影像处理插件)
- 【设计模式】单例模式
- android 版本更新
- linux平台下防火墙iptables原理
- 下载Apache
- 牛刀与小试-dubbo+spring-boot
- 未来值得关注的十大 APP、Web 界面设计趋势
- 用DDK开发的9054驱动
- 广宇修炼困难重重 沃美毫不气馁
- Generative Adversarial Nets论文笔记+代码解析
- spring与memcache的集成