我有一个代码可以检测是否安装了“包名称”,如果没有,则从 URL 下载。
现在一切都很好,但是我想从服务器更新 APK 并且 App 检测是否有新版本可用,并提示用户下载它,并卸载旧版本。
我怎么能用这段代码做到这一点:
- 我正在使用 facebook-lite 应用程序作为示例*
希望有一个例子可以更好地理解,谢谢。
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();
}
}