-
AndroidManifest.xml
<receiver android:name=".OpenDownloadReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.intent.action.DOWNLOAD_COMPLETE" /> <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"/> <data android:mimeType="application/cn.trinea.download.file" /> </intent-filter> </receiver> 实现BroadcastReceiver 接收广播并处理
public class OpenDownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Log.d("DownloadManager", "--download complete: " + intent.getPackage());
long mid = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//Log.d("DownloadManager", "--download complete mid: " + mid);
if (mid <= 0) {
Log.d("DownloadManager", "faild install id: " + mid);
return;
}
install(context, mid);
}
private void install(Context context, long id) {
DownloadManager.Query query = new DownloadManager.Query();
DownloadManager dm = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE);
query.setFilterById(id);
Cursor cus = dm.query(query);
if (cus != null) {
try {
if (cus.moveToFirst()) {
String filename = cus
.getString(cus
.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
//Log.d("DownloadManager", "--download complete filename: " + filename);
int status = cus
.getInt(cus .getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
Uri uri = Uri.fromFile(new File(filename));
if (uri != null) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(uri,
"application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install);
}
}
}
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
cus.close();
}
}
}
- 注册监听
OpenDownloadReceiver downloadRecevier = new OpenDownloadReceiver();
registerReceiver(downloadRecevier, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));