我正在尝试从SD卡以编程方式安装apk而不提及apk的名称。我现在可以做的是我可以安装我在我的代码中命名的apk。但是如果我想在我的设备上安装另一个apk并且为此我必须进入我的代码并更改apk的名称,这不方便。有没有办法在运行时动态获取apk文件的名称?例如获取可安装的apk列表,以便用户可以选择安装哪一个?
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file:///mnt/sdcard/extsd/download /app.apk"),
"application/vnd.android.package-archive");
startActivity(intent);
答案 0 :(得分:2)
更新:之前的代码已删除,因为包含错误。这是一个有效的代码:
public class InstallAPKActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ExtFilter apkFilter = new ExtFilter("apk");
File file[] = Environment.getExternalStorageDirectory().listFiles(apkFilter);
Log.d("InstallApk", "Filter applied. Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
Log.d("InstallApk", "FileName:" + file[i].getName());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file[i]), "application/vnd.android.package-archive");
startActivity(intent);
}
}
class ExtFilter implements FilenameFilter {
String ext;
public ExtFilter(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
}
}
更新2: 该程序只是枚举所有apk文件并将它们写入File数组。之后,它尝试按顺序安装所有这些apk文件。例如,在我的情况下,我将应用程序golddream.apk放在我的模拟器的SD卡上。该应用程序是为SDK v 10开发的。我在logcat中看到以下输出:
12-21 06:44:39.453: D/InstallApk(14897): Filter applied. Size: 1
12-21 06:44:39.453: D/InstallApk(14897): FileName:golddream.apk
12-21 06:44:39.463: I/ActivityManager(62): Starting: Intent { act=android.intent.action.VIEW dat=file:///mnt/sdcard/golddream.apk typ=application/vnd.android.package-archive cmp=com.android.packageinstaller/.PackageInstallerActivity } from pid 14897
12-21 06:44:40.073: I/ActivityManager(62): Displayed com.android.packageinstaller/.PackageInstallerActivity: +578ms (total +1s229ms)