5
我想安裝一個apk文件並設置一個廣播接收器以獲取有關安裝狀態的信息。Android:廣播接收器在應用程序安裝/卸載
我已經準備一個BroadcastReceiver類:
public class newPackageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("DEBUG"," test for application install/uninstall");
}
}
在主活性,我首先註冊一個新的接收器對象,然後實例化按鈕應用程序安裝。
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方法中完成,並且在onDestroy方法中調用unregisterReceiver,所以它應該是有效的。你知道爲什麼嗎 ?
謝謝您的閱讀!
完美〜它的作品!感謝您關於ACTION_PACKAGE_INSTALL〜 – johann
的數據方案和信息工作正常,但是爲什麼? – aotian16