Reputation: 75
I'm beginner for flutter. I built An android App(called "DCS"). A new version of that app(replace.apk) is stored in google drive and shared for public. Size of the app is 20MB. When touch a button, download the apk file from given URL and install the app replacing existing one. I tried using this code. But I was unable to succeed. As I identified, apk file downloading is not complete. Can't find this apk file in device. Please help me.
AndroidManifest.xml
<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"/>
main.dart
import 'package:http/http.dart' as http;
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:open_file/open_file.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String apkUrl =
'https://drive.google.com/uc?export=download&id=1qh2axZcDbj_OZn_4NHI5CUWTR0ocNFiN'; // Replace with your actual Google Drive file ID
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('DCS App'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
downloadAndInstallApk();
},
child: Text('Download and Install DCS App'),
),
),
);
}
Future<void> downloadAndInstallApk() async {
if (await _requestPermission()) {
final directory = await getExternalStorageDirectory();
final savePath = directory!.path + '/replace.apk';
try {
await Dio().download(apkUrl, savePath);
OpenFile.open(savePath);
} catch (e) {
// Handle the error
print('Failed to download APK: $e');
}
} else {
// Handle the scenario where the user denies storage permission
print('Permission Denied');
}
}
Future<bool> _requestPermission() async {
var status = await Permission.storage.status;
if (status.isDenied) {
status = await Permission.storage.request();
}
return status.isGranted;
}
}
Upvotes: 1
Views: 154