我想创建一个可以通过蓝牙发送自己(apk文件)的应用程序。但我找到apk文件路径时遇到麻烦。我试过这段代码:
final PackageManager pm = this.getPackageManager();
List<PackageInfo> packages = pm.getInstalledPackages(PackageManager.GET_META_DATA);
String st = null;
for (PackageInfo packageInfo : packages) {
if(packageInfo.packageName.contains("testbutton"))
st=packageInfo.packageName;
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
String uri = "/data/app/";
uri+=st;
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(uri)));
startActivity(intent);
但是st返回null值。 请帮我解决一下这个。提前谢谢
答案 0 :(得分:4)
无需迭代。获取应用程序本身APK文件uri就像这样简单:
String appUri = getApplicationInfo().publicSourceDir;
另请注意,doc说明了publicSourceDir
:
sourceDir
的公开部分的完整路径, 包括资源和清单。这可能与之不同sourceDir
如果应用程序是前向锁定的。
另请注意,要发送APK文件,您需要将类型设置为application/vnd.android.package-archive
而不是image/*
所以完整的代码片段是:
String appUri = getApplicationInfo().publicSourceDir;
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("application/vnd.android.package-archive");
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(appUri)));
startActivity(Intent.createChooser(sharingIntent, "Share via"));
答案 1 :(得分:3)
最后我找到了正确的答案,感谢@Kanak的帮助:)
PackageManager pm = getPackageManager();
String uri = null;
for (ApplicationInfo app : pm.getInstalledApplications(0)) {
if(!((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1))
if(!((app.flags & ApplicationInfo.FLAG_SYSTEM) == 1)){
uri=app.sourceDir;
if(uri.contains("com.example.test"))
break;
}
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(uri)));
startActivity(intent);
答案 2 :(得分:1)
List<ApplicationInfo> PackageManager.getInstalledApplications() // will give you a list of the installed applications, and
ApplicationInfo.sourceDir //is the path to the .apk file.
PackageManager pm = getPackageManager();
for (ApplicationInfo app : pm.getInstalledApplications(0)) {
Log.d("PackageList", "package: " + app.packageName + ", sourceDir: " + app.sourceDir);
}
输出如下内容:
package: com.tmobile.themechooser, sourceDir: /system/app/ThemeChooser.apk
package: com.tmobile.thememanager, sourceDir: /system/app/ThemeManager.apk
package: com.touchtype.swiftkey, sourceDir: /data/app/com.touchtype.swiftkey-1.apk
package: com.twitter.android, sourceDir: /data/app/com.twitter.android-2.apk
package: fm.last.android, sourceDir: /data/app/fm.last.android-1.apk
所以,这样你就可以找到所有应用程序apk的路径。