Reputation: 315
I am creating an application that installs apps downloaded from a server. I would like to Install these application After the file is downloaded the code for the method I am using to install is here:
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();
}
I would like to have the apk file deleted from the sd card after the install is completed. This code deletes it once the install is started, causing the installation to fail. I am fairly neew to android and would much appreciate some help. I am basically trying to wait for the installation to complete before continuing with the process.
Upvotes: 3
Views: 8786
Reputation: 315
This might not be the best way but I solved the problem. Here is my new code for the method.
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();
}
I created a loop that will wait until the window is in the front to let the method continue executing. The garbage collector and thread sleeping prevents it from slowing down the system or the Linux kernel killing the process. The sleep before the loop is needed so the package manager has time to start before the loop begins.
Upvotes: 4
Reputation: 38180
The Android package manager sends various broadcast intents while installing (or updating / removing) applications.
You can register broadcast receivers, so you will get notifications e.g. when a new application has been installed.
Intents that might be interesting for you are:
Using broadcast receivers is not a big deal:
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);
Upvotes: 12