从 BroadcastReciever 中的 startActivityForResult 获取结果,调用 ACTION



我正在创建一个应用程序,用户可以从中下载其他应用程序并安装它们。现在它工作正常,但它不会在安装后删除apk。我尝试使用BroadcastRecievers但他们似乎不明白何时安装了该应用程序。

目前我正在尝试startActivityForResult,完成后,从Files中删除apk

public class Updater {
private static BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Logger.d("Download completed.");
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath(), downloadApp.getDownloadKey());
Logger.i("Opening: " + file.getAbsolutePath());
Intent openDownloadIntent = getOpenDownloadedApkIntent(context, file);
RelativeLayout progressView = progressViewReference.get();
if (progressView!= null) {
progressView.setVisibility(View.GONE);
}
try {
((Activity) context).startActivityForResult(openDownloadIntent, getResultCode());

} catch (ActivityNotFoundException e) {
// TODO: more robust error handling (show dialog or something)
Logger.e("Exception when launching download intent, message:" + e.getMessage());
}
}
};
private static Intent getOpenDownloadedApkIntent(Context context, File file) {
// The type of intent to use to open the downloaded apk changed in Android N (7.0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri path = FileProvider.getUriForFile(context,
context.getApplicationContext().getPackageName() + ".utils.DownloadedFileProvider",
file);
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setData(path);
return intent;
} else {
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
return intent;
}
}
}

所以我有 2 个方法所在的Updater类(请参阅上面的代码)。并且这个类是由适配器调用的,所以没有地方放onActivityResult.我尝试将其放在调用AdapterActivity中,该调用Updater类,但即使使用EXTRA_RETURN_RESULT也无法到达那里

所以我的问题是..安装完成后如何在此处调用onActivityResult

这是你的活动的伪代码

class DownloadActivity extends AppCompatActivity {
// some of your code here
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// in here you are checking if requestCode is equal to Intent.ACTION_INSTALL_PACKAGE
if(requestCode == Intent.ACTION_INSTALL_PACKAGE and resultCode == ResultCode.OK) {
// Start activity for deleting file
startActivityForResult(Intente.ACTION_DELETE);
}
if(requestCode == Intent.ACTION_DELETE and resultCode == ResultCode.OK) {
// Handling actions after deleted
} 
}
}

当操作结束时,android会调用OnActivityResult。您不必仅在此方法中调用此方法,您可以定义必须执行的操作。

在哪里定义和调用那些 onDownloadComplete 和 getOpenDownloadedApkIntent?

最新更新