Xamarin应用程序,用于以编程方式更新apk 针对市场中的应用对于自定义Web服务中的应用

问题描述

我正在尝试通过从本地Web服务器下载android APK并使用Receiver类的Intent来自动更新android APK。

所以下载效果很好:

  string mime = "application/vnd.android.package-archive";
  string file = "com.fips.sorter.apk";
  string apkurl = "http://myserver/downloads/" + file;
 
  string path = Path.Combine(ExternalStorageDirectory.Path,DirectoryDownloads,file);

  long id = downloadAPK(file,apkurl,mime);

然后实例化一个具体的broadcastReceiver来更新应用程序。

    class Receiver : broadcastReceiver
    {
        private Activity activity;
        private long downloadId;

        public Receiver(Activity activity,long id)
        {
            this.activity = activity;
            this.downloadId = id;
        }

        public override void OnReceive(Context context,Intent intent)
        {
            DownloadManager manager = activity.GetSystemService(Context.DownloadService);
            
            Intent install = new Intent(Intent.ActionView);
            install.SetFlags(ActivityFlags.ClearTop);

            string PATH = $"{ExternalStorageDirectory.Path}/{DirectoryDownloads}/";
            string file = "com.fips.sorter.apk";

            intent.SetDataAndType(Android.Net.Uri.FromFile(new Java.IO.File(PATH + file)),manager.GetMimeTypeForDownloadedFile(downloadId));
            activity.StartActivity(install);

            activity.UnregisterReceiver(this);
            activity.Finish();
        }
    }

.....

  broadcastReceiver onComplete = new Receiver(this,id);
  RegisterReceiver(onComplete,new IntentFilter(DownloadManager.ActionDownloadComplete));

调用activity.StartActivity时,屏幕会要求选择要在其上进行操作的应用,而选择的内容无关紧要,则该应用将停止并且下次不更新该应用。

是否仍可以像这样以编程方式更新应用?该怎么做才能使这项工作?

解决方法

您可以使用以下代码以编程方式在应用程序中安装.apk

针对市场中的应用

Intent goToMarket = new Intent(Intent.ActionView).SetData(Uri.Parse("xxx"));
            StartActivity(goToMarket);

对于自定义Web服务中的应用

Intent promptInstall = new Intent(Intent.ActionView)
    .SetDataAndType(Uri.Parse("file:///path/to/your.apk"),"application/vnd.android.package-archive");
StartActivity(promptInstall);

但是请注意,没有用户权限,我们无法安装应用程序。 因此,我们需要使用 android.permission.REQUEST_INSTALL_PACKAGES:

请求动态请求

有关更多详细信息,您可以检查此doc