笔记 android 自动更新app包案例未运用第三方插件 - json

📅 2026-11-30 👤 拼多多助力营销技巧 📂 首码项目 👁️ 247 次阅读

java代码 核心代码 package com.xxx.app;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;

import androidx.core.app.ActivityCompat;

import androidx.core.content.FileProvider;

import android.Manifest;

import android.content.Context;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.net.Uri;

import android.os.Build;

import android.os.Bundle;

import android.os.Environment;

import android.os.Handler;

import android.os.Message;

import android.os.StrictMode;

import android.util.Log;

import android.view.View;

import android.view.Window;

import android.webkit.WebView;

import android.webkit.WebViewClient;

import org.json.JSONException;

import org.json.JSONObject;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.ProtocolException;

import java.net.URL;

public class MainActivity extends AppCompatActivity {

// 请求接口 验证是否需要更新版本

protected final String ver = "1.1";

protected final Handler handler = new Handler(){

@Override

public void handleMessage(Message msg) {

switch (msg.what) {

case 1: // 接收请求信息

try {

// json 转成字符串

JSONObject jsonObject=new JSONObject(msg.obj.toString());

String ver1 = jsonObject.getString("ver");

String apk = jsonObject.getString("apk");

// 两个版本不相等 则更新下载包

if(!ver.equals(ver1)){

downApkPackage(apk); // 下载更新包

}

} catch (JSONException e) {

e.printStackTrace();

}

break;

case 2: // 按装apk包

installApk(msg.obj.toString()); 拼多多帮助力入口

break;

}

}

};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.activity_main);

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();

StrictMode.setVmPolicy(builder.build());

// 申请权限

permission();

WebView webView = (WebView) findViewById(R.id.webview);

webView.setWebViewClient(new WebViewClient());

webView.getSettings().setJavaScriptEnabled(true);

webView.requestFocus(View.FOCUS_DOWN | View.FOCUS_UP);

webView.loadUrl("https://coin.shenhe99.com/002.html");

}

// 申请权限

public void permission()

{

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

ActivityCompat.requestPermissions(MainActivity.this,new String[]{

Manifest.permission.READ_EXTERNAL_STORAGE, // 读权限

Manifest.permission.WRITE_EXTERNAL_STORAGE, // 写权限

Manifest.permission.INTERNET, // 网络权限

Manifest.permission.INSTALL_PACKAGES, // 网络权限

}, 9999);

};

}

// 验证用户同意处理结果

@Override

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

switch (requestCode){

case 9999:

if (grantResults.length>0&&grantResults[0]== PackageManager.PERMISSION_GRANTED) {

// 自动检测 是否需要更新包

sendHttpContection();

}

break;

}

}

//第一步: 发送HTTP请求

public void sendHttpContection() {

//开启线程,发送请求

new Thread(new Runnable() {

@Override

public void run() {

HttpURLConnection connection = null;

BufferedReader reader = null;

try {

String sendUrl = "https://www.xxx.com/api/apk/update";

URL url = new URL(sendUrl);

connection = (HttpURLConnection) url.openConnection();

//设置请求方法

connection.setRequestMethod("GET");

//设置连接超时时间(毫秒)

connection.setConnectTimeout(5000);

//设置读取超时时间(毫秒)

connection.setReadTimeout(5000);

//返回输入流

InputStream in = connection.getInputStream();

//读取输入流

reader = new BufferedReader(new InputStreamReader(in));

StringBuilder result = new StringBuilder();

String line;

while ((line = reader.readLine()) != null) {

result.append(line);

}

Message msg = Message.obtain();

msg.obj = result.toString();

msg.what = 1;

//发送消息给Handler

handler.sendMessage(msg);

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (ProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (reader != null) {

try {

reader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (connection != null) {//关闭连接

connection.disconnect();

}

}

}}).start();

}

//第二步: 下载App应用

public void downApkPackage(String apkURL){

String fileName = Environment.getExternalStorageDirectory()+ "/Download/update925g.apk";

File file = new File(fileName);

if (!file.getParentFile().exists()) {

file.getParentFile().mkdir();

}

new Thread(new Runnable() {

@Override

public void run() {

String save = fileName;

try {

URL url = new URL(apkURL);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setConnectTimeout(5000);

connection.setRequestMethod("GET");

InputStream inputStream = null;

if (connection.getResponseCode() == 200) {

int totla = 0;

inputStream = connection.getInputStream();

File file = new File(save);

FileOutputStream fos = new FileOutputStream(file);

byte[] bytes = new byte[1024];

int len = 0;

while ((len = inputStream.read(bytes)) != -1) {

fos.write(bytes, 0, len);

totla += (len / 1024);

}

fos.flush();

fos.close();

inputStream.close();

// 下载成功 更新包

Message msg = Message.obtain();

msg.obj = save;

msg.what = 2;

handler.sendMessage(msg);

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}).start();

}

public void installApk1(View view) {

String filePath = Environment.getExternalStorageDirectory()+ "/Download/update925g.apk";

this.installApk(filePath);

}

/**

* 第三步: 安装Apk

*/

public void installApk(String filePath) {

try {

File apkFile = new File(filePath);

if (!apkFile.exists()) {

return;

}

Intent install = new Intent(Intent.ACTION_VIEW);

install.addCategory(Intent.CATEGORY_DEFAULT);

install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//如果想安装完成直接关闭页面注释这句即可

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

//在AndroidManifest中的android:authorities值

Uri apkUri = FileProvider.getUriForFile(this, this.getPackageName() + ".provider", apkFile);

install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

install.setDataAndType(apkUri, "application/vnd.android.package-archive");

} else {

install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");

}

this.startActivity(install);

}catch (Exception exception){

Log.e("-----",exception.toString());

}

}

}

2. MandroidManifest.xml文件

package="com.xxx.app">

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/Theme.App">

android:name="androidx.core.content.FileProvider"

android:authorities="${applicationId}.provider"

android:exported="false"

android:grantUriPermissions="true">

android:name="android.support.FILE_PROVIDER_PATHS"

android:resource="@xml/file_paths" />

3. layout/activity_main.xml文件

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:shrinkMode="safe"

tools:context=".MainActivity">

android:id="@+id/webview"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:focusable="true"

android:layout_weight="1"

/>

按照以上步骤就可以简单实现android app下载功能

相关阅读

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧