-1

我想在新版本可用时显示对话。

我想在我的网络服务器中制作一个 json 文件,我将在 json 文件中手动更新我的应用程序版本。我的应用程序将解析这个 json 文件,并通知用户并显示对话框,通过单击更新按钮从 Playstore 链接更新我的应用程序。

我不想用firebase做这个。

4

1 回答 1

0
public class ForceUpdateAsync extends AsyncTask<String, String, JSONObject>{

private String latestVersion;
private String currentVersion;
private Context context;
public ForceUpdateAsync(String currentVersion, Context context){
    this.currentVersion = currentVersion;
    this.context = context;
}

@Override
protected JSONObject doInBackground(String... params) {

    try 
 {
         latestVersion = Jsoup.connect("https://play.google.com/store/apps/details?id="+context.getPackageName()+"&hl=en")
                .timeout(30000)
                .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                .referrer("http://www.google.com")
                .get()
                .select("div[itemprop=softwareVersion]")
                .first()
                 .ownText();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return new JSONObject();
}

@Override
protected void onPostExecute(JSONObject jsonObject) {
    if(latestVersion!=null){
        if(!currentVersion.equalsIgnoreCase(latestVersion)){
           // Toast.makeText(context,"update is available.",Toast.LENGTH_LONG).show();
            if(!(context instanceof SplashActivity)) {
                if(!((Activity)context).isFinishing()){
                    showForceUpdateDialog();
                }
            }
        }
    }
    super.onPostExecute(jsonObject);
}

public void showForceUpdateDialog(){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(context,
            R.style.DialogDark));

    alertDialogBuilder.setTitle(context.getString(R.string.youAreNotUpdatedTitle));
    alertDialogBuilder.setMessage(context.getString(R.string.youAreNotUpdatedMessage) + " " + latestVersion + context.getString(R.string.youAreNotUpdatedMessage1));
    alertDialogBuilder.setCancelable(false);
    alertDialogBuilder.setPositiveButton(R.string.update, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName())));
            dialog.cancel();
        }
    });
    alertDialogBuilder.show();
}
 }

之后,在您的启动活动中,只需使用此代码

 public void forceUpdate()
{
    PackageManager packageManager = this.getPackageManager();
    PackageInfo packageInfo = null;
    try {
        packageInfo =  packageManager.getPackageInfo(getPackageName(),0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    String currentVersion = packageInfo.versionName;
    new ForceUpdateAsync(currentVersion,BaseActivity.this).execute();
}
于 2018-09-19T12:07:08.890 回答