71 lines
2.7 KiB
C#
71 lines
2.7 KiB
C#
using Android.App;
|
|
using Android.Content;
|
|
using System;
|
|
|
|
namespace XXCpzs.Droid
|
|
{
|
|
[BroadcastReceiver]
|
|
|
|
/// <summary>
|
|
/// 下载通知接收器
|
|
/// </summary>
|
|
public class DownloadReceiver : BroadcastReceiver
|
|
{
|
|
public long downloadId = 0;
|
|
public DownloadReceiver()
|
|
{
|
|
|
|
}
|
|
public DownloadReceiver(long downloadId)
|
|
{
|
|
this.downloadId = downloadId;
|
|
}
|
|
public override void OnReceive(Context context, Intent intent)
|
|
{
|
|
if (intent.Action == DownloadManager.ActionDownloadComplete)
|
|
{
|
|
#region 下载完成
|
|
DownloadManager manager = (DownloadManager)context.GetSystemService(Context.DownloadService);
|
|
//获取下载id,默认值-1
|
|
var downId = intent.GetLongExtra(DownloadManager.ExtraDownloadId, -1);
|
|
if (downId == downloadId)
|
|
{
|
|
Android.Database.ICursor cursor = null;
|
|
try
|
|
{
|
|
DownloadManager.Query query = new DownloadManager.Query();
|
|
query.SetFilterById(downId);
|
|
cursor = manager.InvokeQuery(query);
|
|
if (cursor.MoveToFirst())
|
|
{
|
|
//获取文件下载路径
|
|
var downloadedTo = cursor.GetString(cursor.GetColumnIndex(DownloadManager.ColumnLocalUri));
|
|
//var apkUri = manager.GetUriForDownloadedFile(downId);//错误路径
|
|
|
|
var installIntent = new Intent(Intent.ActionView);
|
|
installIntent.SetDataAndType(Android.Net.Uri.Parse(downloadedTo), "application/vnd.android.package-archive");
|
|
//给目标程序读改uri的权限。
|
|
installIntent.AddFlags(ActivityFlags.NewTask);
|
|
if (Android.OS.Build.VERSION.SdkInt > Android.OS.BuildVersionCodes.M)
|
|
installIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
|
|
// installIntent.SetFlags(ActivityFlags.GrantReadUriPermission | ActivityFlags.NewTask);
|
|
context.StartActivity(installIntent);
|
|
|
|
}
|
|
if (cursor != null)
|
|
cursor.Close();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
}
|
|
|
|
context.UnregisterReceiver(this);
|
|
}
|
|
#endregion
|
|
}
|
|
else if (intent.Action == DownloadManager.ActionNotificationClicked)
|
|
{
|
|
}
|
|
}
|
|
}
|
|
} |