2011-03-03 42 views
3

我正在创建一个应用程序,用于安装从服务器下载的应用程序。我想安装这些应用程序的文件被下载了我使用的安装方法的代码之后是在这里:如何找出安装完成的时间

public void Install(String name) 
{ 
    //prompts user to accept any installation of the apk with provided name 
    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.fromFile(new File 
    (Environment.getExternalStorageDirectory() + "/ContentManager/" + name)), "application/vnd.android.package-archive"); 
    startActivity(intent); 
    //this code should execute after the install finishes 
    File file = new File(Environment.getExternalStorageDirectory() + "/ContentManager/"+name); 
    file.delete(); 

} 

我想有在安装后从SD卡中删除apk文件完成。此代码在安装启动后将其删除,导致安装失败。我相当新鲜的机器人,非常感谢一些帮助。我基本上是在继续这个过程之前,等待安装完成。

+0

这不是一个答案,但更多的是提醒你一个可能性,并可能节省你的时间和精力,可能不被允许的东西。我不确定,也许其他人可以确认,但我认为从除Marketplace之外的任何地方下载应用程序都是不允许的。 – providence 2011-03-03 06:05:56

+0

已经有从我设置的私人服务器上下载应用程序的代码,这个安装代码可以工作,但之后apk文件仍然存在,我希望它被删除。 – Bmoore 2011-03-03 22:43:04

+0

安装后删除应用程序(\ *。apk)的可能的重复](http://stackoverflow.com/questions/15984546/delete-an-application-apk-after-installation) – 2013-10-09 09:36:52

回答

4

这可能不是最好的方法,但我解决了这个问题。这是我的新方法的代码。

public void Install(final String name,View view) 
{ 
    //prompts user to accept any installation of the apk with provided name 
    printstatus("Installing apk please accept permissions"); 
    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.fromFile(new File 
    (Environment.getExternalStorageDirectory() + "/ContentManager/" + name)), "application/vnd.android.package-archive"); 
    startActivity(intent); 
    try { 
     Thread.sleep(1500); 
    } catch (InterruptedException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 
    for(int i=0;i<100;) 
    { 
     System.gc(); 
     if(view.getWindowVisibility()==0) 
     { 
      i=200; 
      System.gc(); 
     } 
     try { 
      Thread.sleep(500); 
      System.gc(); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    File file = new File(Environment.getExternalStorageDirectory() + "/ContentManager/"+name); 
    file.delete(); 
} 

我创建了一个循环,将等待窗口在前面让该方法继续执行。垃圾收集器和线程休眠可以防止它减慢系统或Linux内核的进程。循环之前的休眠是需要的,因此包管理器有时间在循环开始之前启动。

+0

,为什么您要从方法传递视图变量? – 2014-03-06 09:08:35

12

Android 包管理器在安装(或更新/删除)应用程序时发送各种广播意图

您可以注册broadcast receivers,这样您就会收到通知。当一个新的应用程序已经安装。

意图,可能对您感兴趣的是:

使用广播接收机是不是一个大问题:

BroadcastReceiver myReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     // do whatever you want to do 
    } 
}; 

registerReceiver(myReceiver, new IntentFilter("ACTION")); 
unregisterReceiver(myReceiver); 
+0

这段代码看起来像它会工作,但我似乎无法让广播接收器接收任何东西,我在主线程中初始化它,似乎什么都没有发生。任何帮助,将不胜感激。 – Bmoore 2011-03-04 17:23:33

+0

@Bmoore您注册哪种行为?具体如何? – Leo 2011-03-04 23:33:26

+0

我复制了该代码,并将其放在我的类的顶部,并将意图过滤器中的“ACTION”更改为“ACTION_PACKAGE_INSTALL” – Bmoore 2011-03-05 15:08:33