安卓APP自动更新功能实现

uniapp校验app版本并更新 最近用uniapp写了一个安卓壳子做app,遇到一个需求,校验app版本并更新。通过对比线上版本号和app自己的版本号的差异,唤起更新弹窗。 阅读详情

安卓APP自动更新功能实现

前言

安卓App自动更新基本上是每个App都需要具备的功能,接下来介绍一下实现自动更新的步骤。
在这里插入图片描述

代码实现

App自动更新主要分为新版本检测、升级弹窗、下载升级包、安装app这4个步骤,以下为MainActivity的实现代码(注意:目标升级版本和升级包下载地址实际需要向平台拉取):

package com.example.testupgrade;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private final String TAG = "Jason";
    private File file;

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        if(versionCheck()) {
            showTip(this);
        }
    }

	//在主界面显示app版本号,非必要
    private void initView() {
        textView = findViewById(R.id.tv_version);
        textView.setText("version:" + getVersionName());
    }

    //新版本检测
    private boolean versionCheck() {
        String targetVersion = "xxx"; //todo 实际目标版本号应向平台查询

        Log.d(TAG, "versionCheck version:" + getVersionName());
        Log.d(TAG, "versionCheck targetVersion:" + targetVersion);
        if(getVersionName().contentEquals(targetVersion)) {
            return false;
        } else {
            return true;
        }
    }

    //升级弹窗
    private void showTip(Context context) {
        AlertDialog dialog = new AlertDialog.Builder(context).setTitle("升级提示").setMessage("检测到新版本,请升级")
            .setNeutralButton("升级", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    doDownload();
                }
            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
        dialog.setCanceledOnTouchOutside(false);//可选
        dialog.setCancelable(false);//可选
    }

    //下载升级包
    private void doDownload() {

        String downloadUrl = "https://xxx"; //todo 实际下载地址应向平台查询

        String parentPath = "";
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                parentPath = this.getExternalFilesDir(null).getPath();
            } else {
                parentPath = this.getFilesDir().getPath();
            }
        } catch (Exception e) {
            Log.d(TAG, "doDownload e:" + e.getMessage());
        }

        Log.d(TAG, "doDownload parentPath:" + parentPath);
        file = new File(parentPath, "myhouse.apk");
        final String filePath = file.getAbsolutePath();

        //如果已有文件,删除
        if (file.exists()) {
            Log.d(TAG, "doDownload delete APK");
            file.delete();
        }

        try {
            DownloadUtil.get().download(downloadUrl, filePath, new DownloadUtil.OnDownloadListener() {
                @Override
                public void onDownloadSuccess() {
                    //成功
                    Log.d(TAG, "doDownload download success");
                    installApk();
                }

                @Override
                public void onDownloading(int progress) {
                    //进度
                    //Log.d(TAG, "doDownload download:" + progress +"%");
                }

                @Override
                public void onDownloadFailed() {
                    //失败
                    Log.d(TAG, "doDownload download fail");
                }
            });
        } catch (Exception e) {
            Log.d(TAG, "doDownload e2:" + e.getMessage());
        }
    }

    //安装app
    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;

		//7.0以上安卓系统安装app需要通过fileProvider(需要在AndroidManifest.xml声明)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            data = FileProvider.getUriForFile(this, "com.example.testupgrade.provider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Log.d(TAG,"installApk 7.0data:" + data);
        } else {
            data = Uri.fromFile(file);
            Log.d(TAG,"installApk data:" + data);
        }

        intent.setDataAndType(data, "application/vnd.android.package-archive");
        this.startActivity(intent);
    }

    //获取软件版本号
    private String getVersionName() {
        String versionName = "";
        try {
            versionName = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
}

上述下载功能基于okhttp实现的DownloadUtil工具类,具体代码如下:

package com.example.testupgrade;

import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadUtil {
    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;

    public static DownloadUtil get() {
        if (downloadUtil == null) {
            Log.d("Jason", "DownloadUtil get new DownloadUtil");
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    private DownloadUtil() {
        okHttpClient = new OkHttpClient();
    }

    /**
     * @param url 下载连接
     * @param filePath 储存下载文件的SDCard目录
     * @param listener 下载监听
     */
    public void download(final String url, final String filePath, final OnDownloadListener listener) {
        Log.d("Jason", "DownloadUtil download start");
        Request request = new Request.Builder().url(url).build();
        Log.d("Jason", "DownloadUtil request:" + request.toString());
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("Jason", "DownloadUtil onFailure e:" + e.getMessage());
                listener.onDownloadFailed();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("Jason", "DownloadUtil onResponse start");
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                //String savePath = isExistDir(saveDir);
                Log.d("Jason", "DownloadUtil filePath:" + filePath);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    //File file = new File(savePath, getNameFromUrl(url));
                    File file = new File(filePath);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess();
                } catch (Exception e) {
                    Log.d("Jason", "DownloadUtil onResponse e1:" + e.getMessage());
                    listener.onDownloadFailed();
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                        Log.d("Jason", "DownloadUtil onResponse e2:" + e.getMessage());
                    }
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        Log.d("Jason", "DownloadUtil onResponse e3:" + e.getMessage());
                    }
                }
            }

        });
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException
     * 判断下载目录是否存在
     */
    private String isExistDir(String saveDir) throws IOException {
        // 下载位置
        File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        String savePath = downloadFile.getAbsolutePath();
        return savePath;
    }

    /**
     * @param url
     * @return
     * 从下载连接中解析出文件名
     */
    public static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public interface OnDownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess();

        /**
         * @param progress
         * 下载进度
         */
        void onDownloading(int progress);

        /**
         * 下载失败
         */
        void onDownloadFailed();
    }
}

注:为了使用okhttp,需要在build.gradle添加如下配置:

implementation 'com.squareup.okhttp3:okhttp:4.3.1'

为了实现下载和安装功能,需要在AndroidManifest.xml声明网络、SD卡读写和安装包权限;另外,为了实现7.0以上安卓系统的app安装,还需要声明fileProvider,具体代码如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testupgrade">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path" />
        </provider>
    </application>

</manifest>

添加fileProvider对应的file_path.xml
在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <paths>
        <external-path path="" name="download"/>
    </paths>
</resources>

添加network_security_config.xml,配置可访问http地址:
在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>
记录一次uniapp实现APP自动升级 app的版本管理和升级,是一个不可或缺的功能,而uniapp则是提供了一整套的流程,由于官方文档过于复杂,而且写的云里雾里的,所以个人记录一次我的操作,直到配置成功。因为前后端是2个项目,所以我们需要修改更新的云函数,将服务空间指向uni-admin,才能调用更新云函数,参数在服务空间都可以看见。必须要打包apk安装到自己手机才行,我之前使用web端无法检查,以及使用hbuild基座APP也无法检查,这里面内置了升级中心,因为后续还有统计,还要用到uni-admin,所以我们直接用这个更简单。 阅读详情

相关推荐

MAUI + Masa Blazor 开发带自动更新功能的安卓App

自动更新主要下面4个步骤 获取最新版本号 提示用户发现更新,等待用户确认更新 下载最新的apk包 安装apk包

MASAteam的博客 1052

Android APP 自动更新实现(适用Android9.0)

Android App自动更新基本上是每个App都需具备的功能,参考网上各种资料,自己整理了下,先来看看大致的界面: 一、实现思路: 1.发布Android App时,都会生成output-metadata.json文件和对应的apk文件。(不知道如何打包发布apk,可以网上搜一下) 2.output-metadata.json文件里面就记录了发布的程序版本,通过读取此文件来判断是否需要进行更新。 3.更新过程包括: ①下载Apk文件。 ②安装Apk文件。 二、实现步骤: 1.申明权

清山博客 2万+

安卓实现APP的下载更新功能。

使用工具:Android studio以及tomcat服务器。 一、实现方法与原理; 在build.gradle的versioncode和versionname是升级更新的关键。其中versioncode是一个整型的值,代表APP的版本号,而versionname是一个字符串值,表示APP的版本名称。 1、将新版APP的版本信息和新版APP下载地址一同打包保存在JSON文件中,并上传服务器。 2、...

mintan9694的博客 4359

Android实现App内自动升级,适配了安卓7、8及以上版本

应用发布后,要实现灰度升级控制,如果只依赖各家应用市场是不够的,还需要自己在应用中控制升级逻辑。并且每家应用市场上新审核也是一件很麻烦的事情,尤其像这样的应用,甚至没在应用市场上架,更不可能依赖它们了。所以必须要在应用中实现自动升级功能。网上有很多介绍,他们摸索的结果对我有很大帮助。可能是因为版本关系,或者关注点不同,照着做,会有很多过时的或错误的地方,所以我将摸索过程记录在此,防止忘记。下面几个图是在华为荣耀V9(安卓7.0、SDK 24)中的界面:图1、提醒有可升级的版本图2、下载版本。

flyinmind的专栏 6722

Android实现Android APP自动更新 (附完整源码)

Android实现Android APP自动更新 (附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 1313

【HSPiP应用指南】从理论到实践:如何利用汉森溶解度参数优化配方设计

本文深入解析了汉森溶解度参数(HSP)理论及其在配方设计中的核心价值,并详细介绍了如何利用HSPiP软件工具从理论走向实践。文章通过匹配溶解度参数、计算汉森距离(Ra),系统阐述了如何解决溶剂选择、颜料分散稳定性及扩散行为预测等关键问题,并结合界面气相色谱(IGC)等实验方法提升预测精度,旨在帮助配方师实现配方设计的可视化、可量化与高效优化。

weixin_29305313的博客 1646

简单实现安卓app自动更新功能

实现简单安卓app自动更新: 1.服务端提供接口 2.客户端获取接口数据,解析,获取最新版本信息 3.安装最新版本

wuyinlei的博客 2万+

华为设备有关用户名密码的策略配置

命令用来开启对密码进行复杂度检查功能,设备默认已经是开启状态。1、密码长度大于等于12位,含数字大小写字母和特殊符号。2、设置密码更换周期为90天。取值范围8-16,默认长度为8位。登录失败后锁定时间大于15分钟。3、登录失败次数小于5次。4、登录超时30分钟以内。

简单的创作,希望可以帮助到跟我一样的学习者! 7840

安卓app自动更新功能完美实现

零、准备工作 0.1第三方库 implementation ‘io.reactivex.rxjava2:rxjava:2.2.2’ implementation ‘io.reactivex.rxjava2:rxandroid:2.1.0’ implementation ‘io.reactivex.rxjava2:rxkotlin:2.3.0’ implementation ‘com.squareu...

白云天的博客 3万+

ROS应用之如何配置RTOS满足机器人系统中的实时要求

实时操作系统(RTOS)基本概念实时操作系统(RTOS)是设计用于实时应用的操作系统,其主要目标是在确定的时间内完成任务。RTOS的任务调度算法和优先级控制机制能够确保高优先级任务按时完成。精确的传感器数据采集:传感器数据需要在规定时间内采集并传输给控制系统。快速响应外部事件:对于控制系统,需要确保指令在最短的时间内得到响应。任务的调度周期:任务的周期可以通过公式计算,其中 ftask 是任务的调度频率。优先级分配。

weixin_68094467的博客 1008

单细胞测序流程(五)t-sne聚类分析和寻找marker基因

系列文章目录 单细胞测序流程(一)简介与数据下载 单细胞测序流程(二)数据整理 单细胞测序流程(三)质控和数据过滤——Seurat包分析,小提琴图和基因离差散点图 单细胞测序流程(四)主成分分析——PCA 本期主讲内容——t-sne聚类分析和寻找marker基因 介绍:T-SNE是一种用于探索高维数据的非线性降维算法。它将多维数据映射到适合于人类观察的两个或多个维度。 一、课前准备 之前所使用的数据 R语言的IDE 二、过程 聚类分析的目的是根据细胞的差别所进行细胞分群,两个..

qq_45478665的博客 2万+

java编写实现更新_Android实现APP自动更新功能

现在一般的android软件都是需要不断更新的,当你打开某个app的时候,如果有新的版本,它会提示你有新版本需要更新。该小程序实现的就是这个功能。该小程序的特点是,当有更新时,会弹出一个提示框,点击确定,则在通知来创建一个进度条进行下载,点击取消,则取消更新。以下是详细代码:1.创建布局文件notification_item.xml,用于在通知栏生成一个进度条和下载图标。android:layou...

weixin_30899023的博客 1819

AI原生应用在UGC内容审核中的实战经验

AI原生应用(AI-Native Application)——以机器学习模型为核心驱动力,深度整合数据、算法、工程架构的完整系统——为破解这一三角难题提供了全新范式。全链路数据驱动:从数据采集、模型训练到决策优化,形成闭环自治系统,无需人工规则干预多模态深度理解:同时处理文本、图像、音频、视频等多类型内容,理解语义而非简单匹配特征自适应进化能力:通过人机协同反馈持续学习新型违规模式,模型周级迭代成为常态审核效率提升300%:单条视频审核耗时从2.3秒降至0.7秒。

AI算力网络与通信的博客 1149

java app自动更新_简单实现安卓app自动更新功能

简单实现安卓自动更新一般的安卓app都有自动更新功能,实现app的更新,以让用户体验新版本的功能,这里也是项目中用到的,今天就来总结一下,代码应该有点多,还请耐心点哈。安卓应用实现自动更新比较简单,这里跟大家介绍下:第一步 服务器端:服务端提供一个借口,或者网址,我这里就用的服务器是tomcat,这里提供一个网址如下://也就是一个json数据接口public static final Strin...

weixin_39627361的博客 2212

手把手教你用Logisim搞定华科计组实验:单总线CPU硬布线控制器设计(含Excel自动生成电路技巧)

本文详细解析了如何使用Logisim完成华科计组实验中的单总线CPU硬布线控制器设计,特别分享了利用Excel自动生成电路逻辑的高效技巧。从实验准备、状态机表格填写到模块化构建和系统联调,提供全流程实战指导,帮助读者快速掌握计算机组成原理核心概念,大幅提升实验效率。

weixin_28744423的博客 321

学习STM32的DS18B20温度传感器

该函数首先复位传感器,然后发送跳过ROM命令和转换命令,并等待转换完成。接下来,它再次复位传感器,发送跳过ROM命令和读取温度命令。最后,它读取温度值的最低字节和最高字节,并将其组合成16位温度值。传感器的VCC引脚连接到STM32的3.3V电源,GND引脚连接到GND,而数据引脚连接到任何一个IO引脚。需要注意的是,示例代码中使用了一个简单的延时函数来等待转换完成。实际上,您可能需要使用定时器或其他更精确的延时方法来实现更准确的延时。下面是一个示例代码,演示如何读取DS18B20传感器的温度值。

m0_75244442的博客 1182

Android实现APP自动更新功能

现在一般的android软件都是需要不断更新的,当你打开某个app的时候,如果有新的版本,它会提示你有新版本需要更新。该小程序实现的就是这个功能。 该小程序的特点是,当有更新时,会弹出一个提示框,点击确定,则在通知来创建一个进度条进行下载,点击取消,则取消更新。 以下是详细代码: 1.创建布局文件notification_item.xml,用于在通知栏生成一个进度条和下载图标。 <Rel

记录移动开发相关的知识 6375

基于STM32L4XX、HAL库的IP101GRI以太网收发器(PHY)驱动程序设计

define IP101GRI_PHY_ADDRESS 0x01 // 根据硬件设计设置PHY地址。#define IP101GRI_PHYSTS 0x10 // PHY状态寄存器。#define IP101GRI_PHYINIR 0x12 // PHY中断寄存器。#define IP101GRI_PHYCR 0x14 // PHY控制寄存器。#define IP101GRI_PHYID2 0x03 // PHY标识符2。

zhusl6688的博客 721

android自动更新源代码,Android应用APP自动更新功能的代码实现

由于Android项目开源所致,市面上出现了N多安卓软件市场。为了让我们开发的软件有更多的用户使用,我们需要向N多市场发布,软件升级后,我们也必须到安卓市场上进行更新,给我们增加了工作量。因此我们有必要给我们的Android应用增加自动更新的功能。既然实现自动更新,我们首先必须让我们的应用知道是否存在新版本的软件,因此我们可以在自己的网站上放置配置文件,存放软件的版本信息:2baidu_xinwe...

weixin_39981093的博客 848

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Android实现APP版本自动更新功能

Android实现APP自动更新功能 现在一般的android软件都是需要不断更新的,当你打开某个app的时候,如果有新的版本,它会提示你有新版本需要更新。该小程序实现的就是这个功能。 该小程序的特点是,当有更新时,会弹出一个提示框,点击确定,则在通知来创建一个进度条进行下载,点击取消,则取消更新。 以下是详细代码: 1.创建布局文件notification_item.xml,用于在通

u011506413的博客 8276

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

[Phonegap+Sencha Touch] 移动开发67 安卓实现 新版提示更新并下载安装(自动更新插件)

这是一个可以自动更新phonegap android app 的plugin,能显示下载进度条,下载完自动安装 插件地址: https://github.com/lovelyelfpop/androidUpdatePlugin 一、使用命令添加插件: phonegap plugin add https://github.com/lovelyelfpop/androidUpd

小桥流水丿小溪 4257

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

android开发游记:APP自动更新功能的快速集成和实现方法讲解

android的开发有时候让人很蛋疼,比如说app的更新,像ios的更新都被app store包办了方便快捷,但是国内的安卓市场却五花八门,途径各种各样。不要太期望像苹果那样把更新全权交个某夹或者某0,app内都要自己继承一个自动更新的功能。那我们就要自己实现一个。效果图如下: 更新分成2种,一种是普通更新(如上图1)用户可以选择不更新,一种是强制更新(如上图2),新版本已经不再向下兼容,更新时会锁

liaoinstan的博客 9981

android App版本升级功能

一般的安卓app都有自动更新功能,实现app的更新,以让用户体验新版本的功能,这里也是项目中用到的,今天就来总结一下。做和记录。import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; impo...

可乐的博客 3301

Android 云服务器的搭建和友盟APP自动更新功能的实现

setContentView(R.layout.activity_splash); //Bmob SDK初始化--只需要这一段代码即可完成初始化 //请到Bmob官网(http://www.bmob.cn/)申请ApplicationId,具体地址:http://docs.bmob.cn/android/faststart/index.htm...

weixin_34174132的博客 119
上一篇: Android Studio Git功能使用
下一篇: Android Studio生成自定义apk和aar名称(带编译时间)
Jason_Flash
博客等级 码龄7年 1万+粉丝 51原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值