简体   繁体   English

从市场以外的网站以编程方式在 android 设备上下载、安装和删除 .apk 文件

[英]Download, Installing and Delete .apk file on android device programmatically from a website other than marketplace


I've developed some android games and created .apk file..我开发了一些 android 游戏并创建了 .apk 文件..
I've put these .apk files on my website (say: http://www.sush19.com/androidApp/apk/myGame1.apk ) Is it possible to directly install this game when this url visit from another app onClick() event.我已将这些 .apk 文件放在我的网站上(例如: http ://www.sush19.com/androidApp/apk/myGame1.apk )当此 url 从另一个应用程序访问时是否可以直接安装此游戏onClick()事件。

I don't want user to download .apk fine to their sdcard and then install manually, infact the game should be installed directly to the device.我不希望用户将 .apk 下载到他们的 SD 卡然后手动安装,事实上游戏应该直接安装到设备上。

I was trying below code in my another app onClick() event:我在我的另一个应用程序onClick()事件中尝试以下代码:

Intent goToMarket = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.sush19.com/androidApp/apk/myGame1.apk"));
startActivity(goToMarket);

I know the above code is not correct.. but can anyone comment on this..我知道上面的代码不正确..但是任何人都可以对此发表评论..

The below code, allow user to Download, Install and Delete .apk file on Android device.以下代码允许用户在 Android 设备上下载、安装和删除 .apk 文件。 I've created an Android app (Say App1), which downloads other android apps on SD card.我创建了一个 Android 应用程序(比如 App1),它可以在 SD 卡上下载其他 Android 应用程序。 On Button click in App1, it will download the .apk file from my own website on Background, on download complete it will prompt user to install the app downloaded recently from App1 and after the installation is completed the downloaded .apk file will be deleted from the SD card.在App1中点击按钮,它将从我自己的网站后台下载.apk文件,下载完成后会提示用户安装最近从App1下载的应用程序,安装完成后下载的.apk文件将从中删除SD 卡。

In my App1 main activity: I've included button在我的 App1 主要活动中:我已包含按钮
In my case I'm launching my other applications from App1, if not installed on the device, I'm downloading it from my website and installing it.在我的情况下,我从 App1 启动我的其他应用程序,如果未安装在设备上,我将从我的网站下载并安装它。
button click event method按钮点击事件方法

public OnClickListener ButtonClicked = new OnClickListener() {
        public void onClick(View v) {
            Intent i;
            PackageManager manager = getPackageManager();
            try {
                i = manager.getLaunchIntentForPackage("com.mycompany.mygame");
                if (i == null)
                    throw new PackageManager.NameNotFoundException();
                i.addCategory(Intent.CATEGORY_LAUNCHER);
                startActivity(i);
            } catch (PackageManager.NameNotFoundException e) {
                InstallAPK downloadAndInstall = new InstallAPK();
                progress.setCancelable(false);
                progress.setMessage("Downloading...");
                downloadAndInstall.setContext(getApplicationContext(), progress);
                downloadAndInstall.execute("http://xyz/android/gamedownload.aspx?name=mygame.apk");
            }
        }
    };

InstallAPK Class

public class InstallAPK extends AsyncTask<String,Void,Void> {

    ProgressDialog progressDialog;
    int status = 0;

    private Context context;
    public void setContext(Context context, ProgressDialog progress){
        this.context = context;
        this.progressDialog = progress;
    }

    public void onPreExecute() {
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(String... arg0) {
        try {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            File sdcard = Environment.getExternalStorageDirectory();
            File myDir = new File(sdcard,"Android/data/com.mycompany.android.games/temp");
            myDir.mkdirs();
            File outputFile = new File(myDir, "temp.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            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.flush();
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(sdcard,"Android/data/com.mycompany.android.games/temp/temp.apk")), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            context.startActivity(intent);


        } catch (FileNotFoundException fnfe) {
            status = 1;
            Log.e("File", "FileNotFoundException! " + fnfe);
        }

        catch(Exception e)
        {
            Log.e("UpdateAPP", "Exception " + e);
        }
        return null;
    }

    public void onPostExecute(Void unused) {
        progressDialog.dismiss();
        if(status == 1)
            Toast.makeText(context,"Game Not Available",Toast.LENGTH_LONG).show();
    }
}

To delete downloaded file from SD card I've used BroadcastReceiver class要从 SD 卡中删除下载的文件,我使用了 BroadcastReceiver 类

@Override
    public void onReceive(Context context, Intent intent) { 

        try
        {
            String packageName = intent.getData().toString() + getApplicationName(context, intent.getData().toString(), PackageManager.GET_UNINSTALLED_PACKAGES);

            if(intent.getAction().equals("android.intent.action.PACKAGE_ADDED")){
                File sdcard = Environment.getExternalStorageDirectory();
                File file = new File(sdcard,"Android/data/com.mycompany.android.games/temp/temp.apk");
                file.delete();
            }
        }catch(Exception e){Toast.makeText(context, "onReceive()", Toast.LENGTH_LONG).show();}
    }

Don't forget to include following permission in the AndroidManifest.xml不要忘记在 AndroidManifest.xml 中包含以下权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

In my website, I create two .aspx pages and placed it inside Android folder and .apk files inside Android/Games folder in Visual Studio在我的网站中,我创建了两个 .aspx 页面并将其放置在 Android 文件夹中,并将 .apk 文件放置在 Visual Studio 中的 Android/Games 文件夹中
First page: marketplace.aspx.cs第一页:marketplace.aspx.cs

public partial class marketplace : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/Android/Games"));
            int counter = 0;
            foreach (FileInfo file in directory.GetFiles())
            {
                HyperLink link = new HyperLink();
                link.ID = "Link" + counter++;
                link.Text = file.Name;
                link.NavigateUrl = "gamedownload.aspx?name=" + file.Name;

                Page.Controls.Add(link);
                Page.Controls.Add(new LiteralControl("<br/>"));

            }
        }

        protected void Click(object sender, EventArgs e)
        {
            Response.Redirect("gamedownload.aspx");
        }
    }

Second Page: gamedownload.aspx.cs第二页:gamedownload.aspx.cs

public partial class gamedownload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string fileName = Request.QueryString["name"].ToString();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.TransmitFile(Server.MapPath("~/Android/Games/" + fileName));
            Response.End();
        }
    }

I added following code in Web.config file我在 Web.config 文件中添加了以下代码

<system.webServer>
    <staticContent>
      <mimeMap fileExtension=".apk"
               mimeType="application/vnd.android.package-archive" />
    </staticContent>
  </system.webServer>

I hope this information will be help full for some people.我希望这些信息对某些人有所帮助。

Who is maintaining server for your apk because for this you have to do some server setting: set the MIME type of your folder on server containing this apk file as .apk and application/vnd.android.package-archive .谁在为您的 apk 维护服务器,因为为此您必须进行一些服务器设置:将包含此 apk 文件的服务器上的文件夹的 MIME 类型设置为.apkapplication/vnd.android.package-archive Then it will automatically get installed on clicking the link similarly as that of any other app from google play.然后它会在点击链接时自动安装,就像谷歌播放的任何其他应用程序一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM