notification自动更新

本文介绍了一个用于Android应用的后台更新服务实现方案。该方案通过自定义服务类进行应用的远程下载,并利用Notification显示下载进度,完成下载后安装新版本。此外,还包括了版本检查逻辑,确保应用版本的一致性和及时更新。
JsonResponseHandleMSJQ handler_version_new = new JsonResponseHandleMSJQ(this) {
        @Override
        public void onSuccess(JSONArray jsonArray) {
            try {

                String versionUrl = null;
                List<Bean_Dict_Version_New> mListVersion = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<Bean_Dict_Version_New>>() {
                }.getType());
                String versionCode = "";
                String versionDesc = "";
                for (Bean_Dict_Version_New bean_dict_version : mListVersion) {
                    if ("android".equals(bean_dict_version.getPlatForm())) {
                        if ("labx_share".equals(bean_dict_version.getAppName())) {
                            versionCode = bean_dict_version.getAppVersion();
                            versionUrl = Utils.getStrPathPic(ActSplash.this, bean_dict_version.getFilePathValue());
                            versionDesc = bean_dict_version.getVersionChangeDesc();
                            break;
                        }
                    }
                }

                // 获取当前软件包信息
                PackageInfo pi = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), PackageManager.GET_CONFIGURATIONS);
                // 当前软件版本号
                String versionLocal = pi.versionName;
                Timber.e("local:" + versionLocal + "server:" + versionCode);
                if (!TextUtils.isEmpty(versionCode)) {
                    if (!versionCode.equals(versionLocal)) {
                        final String finalVersionUrl = versionUrl;
                        if (isAvailable) {

                            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
                            alertDialog.setPositiveButton("更新", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    Intent intent = new Intent(ActSplash.this, UpdateService.class);
                                    intent.putExtra("url", finalVersionUrl);
                                    startService(intent);
                                    goToNextAct();
                                }
                            });
                            alertDialog.setNegativeButton("忽略", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    goToNextAct();
                                }
                            });
                            alertDialog.setTitle("新版更新提示");
                            alertDialog.setMessage(versionDesc);
                            alertDialog.setCancelable(false);
                            alertDialog.create().show();
                        } else {

                            new SharedPreferencesHelper(ActSplash.this).LogOut();

                            AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
                            alertDialog.setPositiveButton("立刻更新", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    Intent intent = new Intent(ActSplash.this, UpdateService.class);
                                    intent.putExtra("url", finalVersionUrl);
                                    startService(intent);
                                }
                            });
                            alertDialog.setNegativeButton("退出应用", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    finish();
                                }
                            });
                            alertDialog.setTitle("新版更新提示");
                            alertDialog.setMessage(versionDesc);
                            alertDialog.setCancelable(false);
                            alertDialog.create().show();
                        }
                    } else {
                        goToNextAct();
                    }
                } else {
                    goToNextAct();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

2,updateService

package com.weilaifu.aqbx.base;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.weilaifu.aqbx.R;
import com.weilaifu.aqbx.act.ActMain;
import com.weilaifu.aqbx.util.Utils;
import com.weilaifu.msjqlib.util.UtilTools;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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;

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;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        UtilTools.showToast(getApplicationContext(), R.string.text_toast_update);
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        notification = new Notification();
//        notification.icon = android.R.drawable.stat_sys_download;
//        //notification.icon=android.R.drawable.stat_sys_download_done;
//        notification.tickerText = getString(R.string.app_name) + getString(R.string.text_app_update);
//        notification.when = System.currentTimeMillis();
//        notification.defaults = Notification.DEFAULT_LIGHTS;

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ActMain.class), 0);

        Notification.Builder builder = new Notification.Builder(UpdateService.this);
        builder.setSmallIcon(R.drawable.ic_logo)
                .setTicker(getString(R.string.app_name) + "正在更新")
                .setContentTitle(getString(R.string.app_name))
                .setContentIntent(contentIntent);
        views = new RemoteViews(getPackageName(), R.layout.update);
        builder.setContent(views);

        notification = builder.getNotification();
        nm.notify(notificationId, notification);

        myHandler = new MyHandler(Looper.myLooper(), this);

        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();
                    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(), "/" + Utils.DIR);
                        if (!rootFile.exists() && !rootFile.isDirectory())
                            rootFile.mkdir();

                        tempFile = new File(Environment.getExternalStorageDirectory(),

                                "/" + Utils.DIR + "/" + 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);

                            if (precent - download_precent >= 5) {
                                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();
    }


    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;
                        nm.notify(notificationId, notification);
                        break;
                    case 4:
                        nm.cancel(notificationId);
                        break;
                }
            }
        }
    }


    //---------------------------------------------------------------------


    /**
     * �������ؿ�
     */
    private void showDownloadDialog() {
//        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//        builder.setTitle("�汾������...");
//        final LayoutInflater inflater = LayoutInflater.from(mContext);
//        View v = inflater.inflate(R.layout.dialog_download, null);
//        progressBar = (NumberProgressBar) v.findViewById(R.id.pb_dialog_download);
//        builder.setView(v);
//        builder.setNegativeButton("ȡ��", new DialogInterface.OnClickListener() {
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//                //��ֹ����
//                isInterceptDownload = true;
//            }
//        });
//        dialogDownload = builder.create();
//        dialogDownload.show();
//
//        //����apk
//        Thread downLoadThread = new Thread(downApkRunnable);
//        downLoadThread.start();
    }

    // ���ؽ����
//    private NumberProgressBar progressBar;
    // �Ƿ���ֹ����
    private boolean isInterceptDownload = false;
    //�������ʾ��ֵ
    private int progress = 0;

    /**
     * �ӷ����������°�apk���߳�
     */
    private Runnable downApkRunnable = new Runnable() {
        @Override
        public void run() {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //���û��SD��
//                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//                builder.setTitle("��ʾ");
//                builder.setMessage("��ǰ�豸��SD��������޷�����");
//                builder.setPositiveButton("ȷ��", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                });
//                builder.show();
            } else {
                try {
                    //���������°�apk��ַ
                    URL url = new URL("");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/updateApkFile/");
                    if (!file.exists()) {
                        //����ļ��в�����,�
一、项目参加人员、负责内容以及技术特长: "主要人员 "负责内容 "技术特长 " " "自制稳压电源的设计,撰 "数字电路设计,应用软件 " " "写论文电路精度的调节, " " " "键盘、数控部分、数字显 "单片机编程以及电路设计 " " "示的设计,单片机编程 " " " "D/A转换以及精度,输出电"模拟电路设计 " " "路的设计 " " 二、项目背景 数控直流稳压电源是电子技术常用的设备之一,广泛的应用于教学、科研等领域。传 统的多功能直流稳压电源功能简单、难控制、可靠性低、干扰大、精度低且体积大、复 杂度高。普通直流稳压电源品种很多, 在家用电器和其他各类电子设备中,通常都需要电压稳定的直流电源供电。但在实际生 活中,都是由220V 的交流电网供电。这就需要通过变压、整流、滤波、稳压电路将交流电转换成稳定的直 流电。滤波器用于滤去整流输出电压中的纹波,一般传统电路由滤波扼流圈和电容器组 成,若由晶体管滤波器来替代,则可缩小直流电源的体积,减轻其重量,且晶体管滤波 直流电源不需直流稳压器就能用作家用电器的电源,这既降低了家用电器的成本,又缩 小了其体积,使家用电器小型化。 电源技术尤其是数控电源技术是一门实践性很强的工程技术,服务于各行各业。电力 电子技术是电能的最佳应用技术之一。当今电源技术融合了电气、电子、系统集成、控 制理论、材料等诸多学科领域。随着计算机和通讯技术发展而来的现代信息技术革命, 给电力电子技术提供了广阔的发展前景,同时也给电源提出了更高的要求。随着数控电 源在电子装置中的普遍使用,普通电源在工作时产生的误差,会影响整个系统的精确度 。电源在使用时会造成很多不良后果,世界各国纷纷对电源产品提出了不同要求并制定 了一系列的产品精度标准。只有满足产品标准,才能够进入市场。 随着经济全球化的发展,满足国际标准的产品才能获得进出的通行证。数控电源是从 80年代才真正的发展起来的,期间系统的电力电子理论开始建立。这些理论为其后来的 发展提供了一个良好的基础。在以后的一段时间里,数控电源技术有了长足的发展。但 其产品存在数控程度达不到要求、分辨率不高、功率密度比较低、可靠性较差的缺点。 因此数控电源主要的发展方向,是针对上述缺点不断加以改善。单片机技术及电压转换 模块的出现为精确数控电源的发展提供了有利的条件。新的变换技术和控制理论的不断 发展,各种类型专用集成电路、数字信号处理器件的研制应用,到90年代,己出现了数 控精度达到0.05V的数控电源,功率密度达到每立方英寸50W的数控电源。目前在电力电 子器件方面,几乎都为旋纽开关调节电压,调节精度不高,而且经常跳变,使用麻烦。 随着人们生活水平的不断提高,数字化控制无疑是人们追求的目标之一,它所给人带来的 方便也是不可否定的,其中数控制直流稳压电源就是一个很好的典型例子。但人们对它的 要求也越来越高,要为现代人工作、科研、生活提供更好的更方便的设施,就需要从数字 电子技术入手,一切向数字化和智能化方向发展。 数字化智能电源模块是针对传统智能电源模块的不足提出的,数字化能够减少生产过 程中的不确定因素和人为参与的环节数,有效地解决电源模块中诸如可靠性、智能化和 产品一致性等工程问题,极大地提高生产效率和产品的可维护性。 三、主要研究内容 一、设计任务 设计出有一定输出电压范围和功能的数控电源。 其原理示意图如下: +10V -10V +5V 220V 二、设计要求 1.基本要求 (1)输出电压:范围 0~+9.9V,步进 0.1V,纹波不大于 10mV; (2)输出电流:500mA; (3)输出电压值由数码管显示; (4)由"+"、"-"两键分别控制输出电压步进增减; (5)为实现上述几部件工作,自制一稳压直流电源,输出±10V,+5V。 2.发挥部分 (1)输出电压可预置在 0~9.9V 之间的任意一个值; (2)用自动扫描代替人工按键,实现输出电压变化(步进 0.1V 不变); (3)扩展输出电压种类(比如三角波等)。 四、总体思路与研究方案 1. 总体思路 随着时代的发展,数字电子技术已经普及到我们生活、工作、科研等各个领域,本文 将介绍一种数控直流电源,本电源由电源电路、显示电路、控制电路、数模转换电路四 部分组成。准确说就是电源电路提供各个芯片电源、数码管、放大器所需电压,显示电 路用于显示电源输出电压的大小,同时分析了数字技术和模拟技术相互转换的概念。与 传统的稳压电源相比具有操作方便,电源稳定性高以及其输出电压大小采用数码显示的 特点。 数控电压源是最常用的仪器设备,在科研及实验中都是必不可少的。目前所使用的直 流可调电源中,几乎都为旋纽开关调节电压,调节精度不高,而且经常跳变,使用麻烦 。利用数控电压源,可以达到每步0.1V的精度,输出电压范
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值