1.添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2.创建一个广播,进行全局广播监听
public class UsbUpGradeReceiver extends BroadcastReceiver {
private final static String U_DISK_FILE_NAME = "包名.apk";
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case Intent.ACTION_MEDIA_MOUNTED:
// 获取挂载路径, 读取U盘文件
Uri uri = intent.getData();
if (uri != null) {
String filePath = uri.getPath();
File rootFile = new File(filePath);
for (File file : rootFile.listFiles()) {
// 文件列表,进行相应操作...
if (file.getName().equals(U_DISK_FILE_NAME)) {
try {
String authority = context.getApplicationContext().getPackageName() + ".fileprovider";
Uri fileUri = FileProvider.getUriForFile(context, authority, file);
PackageManager pm = context.getPackageManager();
PackageInfo pkgInfo = pm.getPackageArchiveInfo(file.getPath(), PackageManager.GET_ACTIVITIES);
if (pkgInfo != null) {
ApplicationInfo appInfo = pkgInfo.applicationInfo;
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
LogUtils.e(info.packageName + " " + info.versionName + " " + info.versionCode);
if (appInfo.packageName.equals(info.packageName)) {
if (pkgInfo.versionCode > info.versionCode) {
Intent intents = new Intent(Intent.ACTION_VIEW);
intents.setDataAndType(fileUri, "application/vnd.android.package-archive");
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intents.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intents);
} else {
ToastUtils.showLong("当前需要安装的apk小于当前版本,请检查apk文件");
}
} else ToastUtils.showLong("当前需要安装apk不正确,请检查apk文件!");
}
break;
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(e);
}
}
}
}
break;
}
}
}
3.注册全局广播,并添加相应监听事件
<receiver
android:name=".UsbUpGradeReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MEDIA_CHECKING" />
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<action android:name="android.intent.action.MEDIA_EJECT" />
<action android:name="android.intent.action.MEDIA_UNMOUNTED" />
<data android:scheme="file" />
</intent-filter>
</receiver>
4.在res/xml文件夹中创建 file_paths.xml 物理地址文件. 并在AndroidMaindest中引用
<paths>
<external-path
name="files_root"
path="Android/data/com.ruihan.handrehabilitation/" />
<external-path
name="external_storage_root"
path="." />
<root-path name="root" path="/"/>
</paths>
<permission-group android:name="${applicationId}.andpermission" />
<application>
<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/file_paths" />
</provider>
</application>