If you want to install a custom app dynamically from your app, then it is quite simple. For this, you need to place APK on a downloadable URL, so that it can be downloaded directly. Then you can access app url and install. Since you want to install app from your app, then you need to download the APK first and then install your custom app. It thus need to do in background.
Here is the code.
I installed custom app on launch of my app i.e. MainActivity
//Download APK and then Install Custom App
InstallApp customApp= new InstallApp();
customApp.setContext(myContext);
customApp.execute("http://APK-URL/AppName.apk");
Following is the code to download the apk in background then install app.
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class InstallApp extends AsyncTask<String,Void,Void> {
private Context context;
private final String TAG = "InstallApp";
public void setContext(Context context){
this.context = context;
}
@Override
protected Void doInBackground(String... apk_url) {
try {
//URL of the APK, to download
URL download_url = new URL(apk_url[0]);
HttpURLConnection c = (HttpURLConnection) download_url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
//Download APK to download folder. Save APK file with CustomApp.apk
File file = new File(Environment.getExternalStorageDirectory() + "/download/");
file.mkdirs();
File downloadFile= new File(file, "CustomApp.apk");
if(downloadFile.exists()){
downloadFile.delete();
}
FileOutputStream fos = new FileOutputStream(downloadFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int lenght = 0;
while ((lenght = is.read(buffer)) != -1) {
fos.write(buffer, 0, lenght);
}
fos.close();
is.close();
//Install App Intent
Intent install_intent = new Intent(Intent.ACTION_VIEW);
install_intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "CustomApp.apk")), "application/vnd.android.package-archive");
install_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install_intent);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return null;
}
}
Similarly, if you want to uninstall app from another app, then here is code:
//Uninstall app
Similarly, if you want to uninstall app from another app, then here is code:
//Uninstall app
Uri packageUri = Uri.parse("package:"+"name of app package");
//OS >= 14 supports ACTION_UNINSTALL_PACKAGE
//OS < 14 ACTION_DELETE
//Therefore, for all OS, use the following.
//OS < 14 ACTION_DELETE
//Therefore, for all OS, use the following.
Intent appUninstall= new Intent( (Build.VERSION.SDK_INT >= 14)?Intent.ACTION_UNINSTALL_PACKAGE: Intent.ACTION_DELETE, packageUri);
startActivity(appUninstall);