`
qq986945193
  • 浏览: 92394 次
  • 性别: Icon_minigender_2
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

Android开发必有功能,更新版本提示,检测是否有新版本更新。下载完成后进行安装。

 
阅读更多

作者:程序员小冰,CSDN博客:http://blog.csdn.net/qq_21376985,转载请说明出处。

给大家介绍个东西,MarkDown真的超级超级好用。哈哈。好了,

正题内容如下:

先说明,此文章是教程详解,而不是直接拿来用的Demo,想要Demo的

朋友可以在下面留言或者私信,看到有要的朋友会做一个Demo。下面

文章是教大家理解这个内容。

先看一下效果:


1,检测更新

    /*
     * 从服务器端读取相关信息
     */
    private String getInfoFromServer(String url) throws ClientProtocolException,
            IOException
    {
        // sb 是从updateServerUrl上面读取到的内容
        StringBuffer sb = new StringBuffer();

        HttpClient httpClient = new DefaultHttpClient();
        HttpParams httpParams = httpClient.getParams();
        // 设置网络超时参数
        HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
        HttpConnectionParams.setSoTimeout(httpParams, 5000);
        HttpResponse response = httpClient.execute(new HttpGet(url));
        HttpEntity entity = response.getEntity();
        if (entity != null)
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    entity.getContent(), "UTF-8"), 8192);

            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            reader.close();
        }
        else
        {
            // 如果网络不通则默认初始版本
            sb.append("1");
        }
        Log.i("getInfoFromServer", sb.toString().trim());
        return sb.toString().trim();
    }

    /**
     * 获取软件版本号
     * 
     * @param context
     * @return
     */
    private float getVersionCode(Context context)
    {
        float versionCode = 0;
        try
        {
            // 获取软件版本号,对应AndroidManifest.xml下android:versionCode
            versionCode = Float.valueOf(context.getPackageManager().getPackageInfo(
                    mContext.getPackageName(), 0).versionName);
        }
        catch (NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return versionCode;
    }


    private void showUpdateDialog()
    {
        if (mDialog == null)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示更新");
            builder.setMessage("有最新版本可更新,是否下载更新");
            builder.setPositiveButton("更新", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    // 开启服务进行更新
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, UpgradeService.class);

                    bindService(intent, conn, Context.BIND_AUTO_CREATE);

                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    if (mDialog.isShowing())
                    {
                        mDialog.dismiss();
                    }
                }
            });
            mDialog = builder.create();
        }
        mDialog.show();
    }


2,创建通知,带有自定义视图通知

    1)自定义布局:

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/image"
                android:layout_width="45dp"
                android:layout_height="45dp"
                android:layout_marginTop="2dp"
                android:background="@drawable/ic_launcher" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="3dp"
                android:layout_marginRight="3dp"
                android:orientation="vertical" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="2dp"
                    android:orientation="horizontal" >

                    <TextView
                        android:id="@+id/dw_name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:text="xxxx.apk"
                        android:textSize="18sp"
                        android:textColor="#4b8df9" />

                    <TextView
                        android:id="@+id/tv_progress"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:gravity="center"
                        android:minWidth="60dp"
                        android:textSize="18sp"
                        android:textColor="#4b8df9" />
                </LinearLayout>

                <ProgressBar
                    android:id="@+id/progressbar"
                    style="?android:attr/progressBarStyleHorizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    android:layout_marginRight="4dp"
                    android:layout_marginTop="3dp"
                    android:max="100"
                    android:progress="0"
                    android:text="xxxx.apk" />
            </LinearLayout>
        </LinearLayout>

    2) 通知处理:

    mNotificationManager = (NotificationManager) 
                getSystemService(android.content.Context.NOTIFICATION_SERVICE);

    /**
     * 创建通知
     */
    private void setUpNotification()
    {
        CharSequence tickerText = getString(R.string.download_begin);

        long when = System.currentTimeMillis();

        mNotification = new Notification();
        mNotification.icon = R.drawable.ic_launcher;
        mNotification.tickerText = tickerText;
        mNotification.when = when;

        // 放置在"正在运行"栏目中
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;

        RemoteViews contentView = new RemoteViews(getPackageName(),
                R.layout.download_notification_layout);

        contentView.setTextViewText(R.id.dw_name,
                getString(R.string.tip_apk_download));

        // 指定个性化视图
        mNotification.contentView = contentView;

        Intent intent = new Intent(this, MainActivity.class);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_NO_CREATE);

        // 指定内容意图
        mNotification.contentIntent = contentIntent;
        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }

    通知修改:

    if (rate <= 100)
    {
        RemoteViews contentview = mNotification.contentView;
        contentview.setTextViewText(R.id.tv_progress, rate + "%");
        contentview.setProgressBar(R.id.progressbar, 100, rate, false);
    }
    else
    {
        // 下载完毕后变换通知形式
        mNotification.flags = Notification.FLAG_AUTO_CANCEL;
        // mNotification.contentView = null;

        stopSelf();
    }
    mNotificationManager.notify(NOTIFY_ID, mNotification);



3,下载逻辑处理

    private int lastRate = 0;
    private Runnable mdownApkRunnable = new Runnable()
    {
        @Override
        public void run()
        {
            try
            {
                // 获取下载地址
                URL url = new URL(DOWNLOAD_APK_URL);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File file = new File(savePath);
                if (!file.exists())
                {
                    file.mkdirs();
                }

                file = new File(saveFileName);
                if (file.exists())
                {
                    file.delete();
                }

                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do
                {
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    // 更新进度
                    Message msg = mHandler.obtainMessage();
                    msg.what = 1;
                    msg.arg1 = progress;
                    if (progress >= lastRate + 1)
                    {
                        mHandler.sendMessage(msg);
                        lastRate = progress;
                    }
                    if (numread <= 0)
                    {
                        // 下载完成通知安装
                        mHandler.sendEmptyMessage(0);
                        // 下载完了,cancelled也要设置
                        canceled = true;
                        break;
                    }
                    fos.write(buf, 0, numread);
                }
                while (!canceled);// 点击取消就停止下载.

                fos.close();
                is.close();
            }
            catch (MalformedURLException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }

        }
    };

4,安装APK

    /**
     * 安装apk
     * 
     * @param url
     */
    private void installApk()
    {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists())
        {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        mContext.startActivity(i);

        stopSelf();

        mNotification = null;
    }


<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>
分享到:
评论

相关推荐

    android开发版本更新下载

    版本更新的核心在于检测服务器上的新版本信息,并根据需要下载更新包进行安装。这一过程通常分为几个关键步骤: 1. **版本检查**:应用会定期或在启动时检查服务器上是否有新版本。 2. **新版本信息解析**:如果...

    android提示更新下载安装demo

    本示例"android提示更新下载安装demo"聚焦于如何实现这一过程,通过一个简洁的示例来演示Android应用如何检测新版本,并引导用户进行下载安装。以下是关于这个主题的详细知识点: 1. 版本检查: - `...

    Android版本更新(检测、升级),检测版本,通过apk路径下载安装包

    接下来,当检测到有新版本时,我们需要下载更新包。可以使用`java.net.URL`和`java.io.InputStream`类来实现文件下载,同时通过`ProgressBar`或者自定义进度条组件展示下载进度。在下载过程中,为了用户体验,可以...

    android app内部更新,版本升级

    3. **下载更新**:当检测到新版本后,应用会提示用户下载更新。这通常通过`AsyncTask`或者`DownloadManager`类实现异步下载,以避免阻塞用户界面。下载进度可以通过通知栏更新,提供取消和暂停选项。 4. **安装更新...

    Android提示版本更新----源码

    在Android开发中,提示用户进行版本更新是保持应用软件新鲜度和功能完善性的重要环节。本文将基于提供的源码分析Android应用如何实现自动检测并提示用户进行版本更新的机制。 首先,`try_downloadFile_progress`这...

    android应用下载安装apk升级版本实现demo适配Android10

    7. **更新流程**:在应用内检测新版本通常有两种方式:服务器推送更新信息或定期检查。服务器推送可以通过后台服务、消息推送等方式实现,定期检查则可以在应用启动时执行。 8. **用户界面**:提供友好的UI提示用户...

    android app版本自动检测、更新

    在实际开发中,确保更新功能在不同网络环境、设备和Android版本上都能正常工作,发布新版本时,要遵循Google Play Store或自建应用市场的更新规范。 总之,Android应用的版本自动检测和更新涉及到多个开发环节,...

    Android APP版本更新源码

    通常,这个过程包括检查新版本、下载更新文件(如APK)以及安装更新。以下步骤详细阐述了这一过程: 1. **检查新版本**: - 服务器端维护一个版本信息文件,包含当前最新版本号、更新描述和下载链接。 - 客户端...

    android 版本更新 同时清除旧版本数据

    3. 安装更新:下载完成后,Android系统并不能自动安装非Google Play商店来源的APK,因此需要提示用户手动安装。开发者可以通过Intent来启动系统的安装程序,或者在满足特定条件(如只在Wi-Fi连接下更新)时,自动...

    android 应用更新功能 检测更新 自动下载安装 demo updatedemo

    在Android应用开发中,实现应用自动检测更新、下载并安装的功能是提高用户体验和保持软件最新状态的关键。"updatedemo"通常是指一个示例项目,它展示了如何构建这样的更新机制。以下将详细介绍这个过程中的关键知识...

    Android 版本更新(含自定义更新提示框,自定义更新进度条)

    在Android应用开发中,版本更新是一项重要的功能,它允许用户获取应用的最新版本,修复已知问题并享受新增的功能。自定义更新提示框和更新进度条可以提升用户体验,使其更加符合应用的整体风格,并且能够更好地控制...

    Android版本检测安装

    同时,对于更新检测,开发者通常会通过后台服务或定时任务定期检查服务器上的新版本,并提醒用户更新。 总结,Android版本检测安装是开发者必须掌握的关键技能。正确地检测版本并根据结果执行相应的处理,不仅可以...

    Android检测版本更新

    首先,我们需要理解版本更新的基本流程:检查服务器上的最新版本信息,对比本地应用的版本号,如果存在新版本,提示用户进行更新。这一过程主要涉及网络请求、JSON解析和UI交互等技术。 1. **网络请求**: 使用...

    android 静默安装和普通安装版本更新

    在版本更新场景下,普通安装通常表现为用户收到更新通知,点击后启动安装流程,系统会提示用户更新应用的新特性并请求必要的权限。这种安装方式具有较高的用户参与度,可以确保用户了解更新内容和权限需求,但同时也...

    android版本更新 demo

    这个“android版本更新 demo”项目旨在展示如何实现一个有效的版本更新系统,包括检查新版本、下载更新包以及自动升级等功能。以下是对这些关键知识点的详细解释: 1. **版本控制**:在Android应用开发中,版本控制...

    Android版本更新项目源码

    - 为了检测新版本,应用需要启动一个后台服务,定期向服务器发送请求,查询是否有可用的更新。 - 这个服务通常在应用启动时或者在特定时间间隔运行,通过HTTP请求获取JSON或XML格式的更新信息,包括新版本号、更新...

    android 使用服务器进行版本更新

    4. **下载更新**:当检测到新版本时,启动一个后台服务或使用IntentService下载新APK文件。这里可以利用`DownloadManager`系统服务,它提供了下载任务的调度和管理功能。同时,为了提供下载进度,可以注册广播接收器...

    android版本更新Demo案例

    总结起来,Android版本更新Demo案例的核心包括检测新版本、下载更新包、显示下载进度以及自动安装新版本。这个过程中涉及到网络请求、UI交互、文件操作和权限管理等多个方面的知识。通过实践这样的案例,开发者可以...

    android 版本更新DEMO

    3. **用户通知**:当检测到新版本时,应用会向用户展示更新提示,包含更新内容和提示用户是否立即下载或稍后提醒。 4. **下载管理**:用户选择更新后,应用会启动一个下载任务。可以使用内置的`DownloadManager`...

    android自动检测版本并更新下载,带进度条服务端解析xml

    在Android应用开发中,定期检查并自动更新应用程序是提高用户体验和确保软件安全的重要一环。本项目关注的是如何实现这样一个功能,即“android自动检测版本并更新下载,带进度条服务端解析xml”。这个功能涉及到...

Global site tag (gtag.js) - Google Analytics