Flutter安卓端apk下載安裝

一、思路

  • 1.使用dio下載apk包存放到應(yīng)用的根目錄下
  • 2.使用channel通訊的方式調(diào)用安卓原生方法,使用FileProvider安裝應(yīng)用
    PS:注意需要添加相應(yīng)的權(quán)限 和 配置FileProvider

二、實施

  • 1.dart端創(chuàng)建DownloadAndUpdatePage類 實現(xiàn)下載apk功能,并調(diào)用通道方法安裝apk
import 'package:app_update_plugin/app_update_plugin.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

class DownloadAndUpdatePage extends StatefulWidget {
  final String updateUrl;// 替換為實際的APK下載鏈接

  DownloadAndUpdatePage({required this.updateUrl});

  @override
  _DownloadAndUpdatePageState createState() => _DownloadAndUpdatePageState();
}

class _DownloadAndUpdatePageState extends State<DownloadAndUpdatePage> {
  late String apkPath;

  void _downloadApk() async {
    String downloadUrl = widget.updateUrl; 

    Dio dio = Dio();
    try {
      // 獲取APP的文件目錄路徑
      Directory appDocDir = await getApplicationDocumentsDirectory();
      apkPath = '${appDocDir.path}/update.apk';

      // 下載文件
      await dio.download(downloadUrl, apkPath, onReceiveProgress: (received, total) {
        if (total != -1) {
          // 下載進度
          print((received / total * 100).toStringAsFixed(0) + "%");
        }
      });

      // 下載完成,調(diào)用安裝APK函數(shù)
      _installApk(apkPath);
    } catch (e) {
      print("下載失敗:$e");
    }
  }

Future<void> _installApk(String apkPath) async {
  final plugin = AppUpdatePlugin();
  // AppInstaller.installApk(apkPath);
  print('******************* apkPath ************************\n $apkPath');
  plugin.installApk(apkPath);
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('下載并安裝APK'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _downloadApk,
          child: Text('下載并安裝APK'),
        ),
      ),
    );
  }
}

調(diào)用方式

 Navigator.push(context, MaterialPageRoute(builder: (context){
      return DownloadAndUpdatePage(updateUrl: 'http://xxxxxx.apk',);//替換為實際生產(chǎn)上的apk地址
    }));

通訊代碼

@override
  void installApk(String appPath){
    methodChannel.invokeMethod('installApk',{'apkPath' : appPath});
  }
  • 2.安卓端代碼
    創(chuàng)建ApkInstaller類用于安裝apk
package com.example.app_update_plugin;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.StrictMode;
import androidx.core.content.FileProvider;
import java.io.File;

public class ApkInstaller {

    /**
     * 安裝APK文件
     *
     * @param context  上下文
     * @param apkPath  APK文件的絕對路徑
     */
    public static void installApk(Context context, String apkPath) {
        // 創(chuàng)建File對象
        File apkFile = new File(apkPath);

        // 設(shè)置文件Uri訪問權(quán)限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

        // 安裝APK
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }
}

PS:其中Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);中的context.getPackageName() + ".fileprovider"要和配置文件中的authorities對應(yīng)上(后面會提到)
通訊方法實現(xiàn)

package com.example.app_update_plugin;

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import androidx.core.content.FileProvider;
//import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import android.text.TextUtils;
import android.content.Context;
import android.util.Log;

import com.example.app_update_plugin.ApkInstaller;
// 其他自定義類的導(dǎo)入語句...


/** AppUpdatePlugin */
public class AppUpdatePlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;
  private Context context; // 用于存儲Context

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "app_update_plugin");
    channel.setMethodCallHandler(this);
    // 獲取ApplicationContext并存儲在變量中
    context = flutterPluginBinding.getApplicationContext();
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    Log.e("11111","2222222");
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } else if (call.method.equals("installApk")) {
      String filePath = call.argument("apkPath");
      if (!TextUtils.isEmpty(filePath)) {
        String apkPath = filePath; // APK文件路徑
        ApkInstaller.installApk(context, apkPath);
      } else {
        result.error("installApk", "apkPath is null", null);
      }


    } else {
      result.notImplemented();
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }

}

添加權(quán)限

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

添加FileProvider配置

       <provider
           android:name="androidx.core.content.FileProvider"
           android:authorities="${applicationId}.fileprovider"
           android:exported="false"
           android:grantUriPermissions="true">
           <meta-data
               android:name="android.support.FILE_PROVIDER_PATHS"
               android:resource="@xml/provider_paths" />
       </provider>

PS:其中authorities的內(nèi)容要和安卓端代碼ApkInstaller類中的Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);這行中的context.getPackageName() + ".fileprovider"嚴格對應(yīng)上否則會報錯配置找不到。
在xml/路徑下添加provider_paths.xml文件配置文件訪問路徑 如果沒有這個路徑手動創(chuàng)建一個內(nèi)容如下

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

        <root-path
            name="root"
            path="app_flutter" />

        <external-path
            name="external"
            path="app_flutter" />

        <!--代表外部存儲區(qū)域的根目錄下的文件 Environment.getExternalStorageDirectory()/DCIM/camerademo目錄-->
        <external-path
            name="mq_DCIM"
            path="app_flutter" />

        <!--代表外部存儲區(qū)域的根目錄下的文件 Environment.getExternalStorageDirectory()/Pictures/camerademo目錄-->
        <external-path
            name="mq_Pictures"
            path="app_flutter" />

        <!--代表app 私有的存儲區(qū)域 Context.getFilesDir()目錄下的images目錄 /data/user/0/com.hm.camerademo/files/images-->
        <files-path
            name="mq_private_files"
            path="app_flutter" />

        <!--代表app 私有的存儲區(qū)域 Context.getCacheDir()目錄下的images目錄 /data/user/0/com.hm.camerademo/cache/images-->
        <cache-path
            name="mq_private_cache"
            path="app_flutter" />

        <!--代表app 外部存儲區(qū)域根目錄下的文件 Context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)目錄下的Pictures目錄-->
        <external-files-path
            name="mq_external_files"
            path="app_flutter" />
        <!--代表app 外部存儲區(qū)域根目錄下的文件 Context.getExternalCacheDir目錄下的images目錄-->
        <external-cache-path
            name="mq_external_cache"
            path="app_flutter" />

        <root-path
            name="mq_external_cache"
            path="" />
    </paths>
</PreferenceScreen>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容