Thursday, August 15, 2013

Install APK from assets in android application

Yes, We can install another application from installed application !!!
Sometimes our application is dependent in other application,at that time you need to store application APK file into assets folder and just write code for it. Thats it.

The main benefit is there is no requirement of internet to download application which you need to use in your application.The question arrives in your mind is, how it is possible?
Here is full description for that.



  • Create one folder called rar in assets folder.
  • Copy another application APK and paste it into this rar folder.   
  • Create one button or other component which is used to install APK file.
  • For Example, I choose button for install APK file.
  • Now add below code carefully in MainActivity.java


MainActivity.java




public class MainActivity extends Activity {


Button b;
String rarPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b = (Button) findViewById(R.id.button1);

b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

rarPath = "rar/sms.apk";
AssetManager assetManager = getAssets();

InputStream in = null;
OutputStream out = null;
try {
   in = assetManager.open(rarPath);
   out = new FileOutputStream("/sdcard/myapk.apk");

   byte[] buffer = new byte[1024];

   int read;
   while((read = in.read(buffer)) != -1) {

       out.write(buffer, 0, read);

   }

   in.close();
   in = null;

   out.flush();
   out.close();
   out = null;

   Intent intent = new Intent(Intent.ACTION_VIEW);

   intent.setDataAndType(Uri.fromFile(new File("/sdcard/myapk.apk")),
       "application/vnd.android.package-archive");

   startActivity(intent);

} catch(Exception e) { e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error !",Toast.LENGTH_LONG).show();}
}
});
}
}

Done. Now run the project.

NOTE: If APK file size is more than 2Mb, it will take some time to copy and install it.
Use Thread or AsyncTask for heavy APK file.

4 comments:

  1. THANK YOU VERY MUCH!!!!!!!!!!

    ReplyDelete
  2. Wow, thank you so much sir, i looked so much for this and didn't find it, until i found you.
    I have a question please, how can do that with an apk from a URl ?
    I mean download it from URL and directly save it and call it to install please ?

    ReplyDelete
  3. i got error! whwen click on install button
    can you tell me how to creat rar forlder
    i creat directory for rar and pasted my apk

    ReplyDelete