I Have a code that detect if a "Package-Name" is installed or not, and download it from URL if not.
Everything is good for now, But I want to Update The APK from the server and the App detect if a new version is available , And Prompt the user to download it, and uninstall the old version.
How Can I Do That with this code :
- I'm Using facebook-lite app as example in this*
Hope there is is an example for better understanding, Thank You.
MyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
///// check if package name is installed //////////
final String YOUR_PACKAGE = "com.facebook.lite";
PackageManager packageManager = getPackageManager();
ApplicationInfo applicationInfo = null;
try {
applicationInfo = packageManager.getApplicationInfo(YOUR_PACKAGE, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (applicationInfo == null) {
///// If Not installed it will open your app directly from Url
Update("https://www.dropbox.com/s/jqqbp5eazfs6hto/facebook.apk?dl=1");
} else {
// Open the app If Installed
Intent LaunchIntent = packageManager.getLaunchIntentForPackage(YOUR_PACKAGE);
startActivity(LaunchIntent);
}
}
});
///// =*=*=**=*==*=*=**=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
}
@SuppressLint("StaticFieldLeak")
public void Update(final String apkurl) {
new AsyncTask<Void, String, String>() {
String result = "";
@Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(apkurl);
HttpURLConnection c = (HttpURLConnection) url
.openConnection();
c.setRequestMethod("GET");
c.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "facebook.apk");
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.close();
is.close();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "facebook.apk")),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (IOException e) {
result = "Update error! " + e.getMessage();
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result) {
}
}.execute();
}
}