gpt4 book ai didi

Android:应用程序安装/卸载时的 BroadcastReceiver

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:51:29 28 4
gpt4 key购买 nike

我想安装一个 apk 文件并设置广播接收器以获取有关安装状态的信息。

我准备了一个 BroadcastReceiver 类:

public class newPackageReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Log.d("DEBUG"," test for application install/uninstall");
}

}

在主要 Activity 中,我首先注册一个新的接收器对象,然后实例化应用程序安装按钮。

public void onCreate(Bundle savedInstanceState) {
...
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
filter.addAction(Intent.ACTION_PACKAGE_INSTALL);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);

receiver = new newPackageReceiver();
registerReceiver(receiver, filter);
...

dlButton.setText(R.string.dl_button);
dlButton.setOnClickListener(new AppliDownloadOnClickListener(this ));


@Override
public void onDestroy(){
unregisterReceiver(receiver);
super.onDestroy();
}

在我的 OnclickListener 类中,我输入:

@Override
public void onClick(View v) {

// actually, the below process is in an asyncTask
URL url;
Intent promptInstall;

try {
url = new URL(apkurl);

HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();

String PATH = Environment.getExternalStorageDirectory()+ "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "app.apk");
FileOutputStream fos = new FileOutputStream(outputFile);

InputStream is = c.getInputStream();

byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}

fos.close();
is.close();

promptInstall = new Intent(Intent.ACTION_VIEW);
promptInstall.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");

if (promptInstall != null) {
activity.startActivity(promptInstall);
} else {
ErrorDetails.displayToastMessage(activity,R.string.connection_error);
}


} catch (...) {
...
}

}

使用上面的代码(我已将其缩小),单击按钮时,会显示安装程序并完美安装应用程序,但从未调用接收器类(newPackageReceiver)。注册(registerReceiver)是在onCreate方法中完成的,unregisterReceiver是在onDestroy方法中调用的,所以应该是有效的。你知道为什么吗?

感谢阅读!

最佳答案

您需要添加 data scheme到您的 Intent 过滤器。

filter.addDataScheme("package");

此外,ACTION_PACKAGE_INSTALL从未使用过。

关于Android:应用程序安装/卸载时的 BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14350460/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com