📌  相关文章
📜  为 Android 应用程序的最新更新显示 AlertDialog

📅  最后修改于: 2022-05-13 01:55:46.145000             🧑  作者: Mango

为 Android 应用程序的最新更新显示 AlertDialog

在使用智能手机时,您必须经历过应用程序要求用户更新以进一步使用它的情况。在这里,我们将实现相同的功能,并查看应用程序如何通过显示更新警报对话框来要求用户更新它。

我们要在这个应用程序中构建什么?

这是我们将在此应用程序中实现的示例视频。请注意,我们将为此项目使用Java语言。

分步实施

第 1 步:创建一个新项目

  • 打开一个新项目。
  • 我们将使用Java语言开发 Empty Activity。保持所有其他选项不变。
  • 在您方便的时候命名应用程序。
  • 将有两个名为 activity_main.xml 和 MainActivity 的默认文件。Java

如果您不知道如何在 Android Studio 中创建新项目,可以参考如何在 Android Studio 中创建/启动新项目?

步骤 2. 添加所需的依赖项

导航到 Gradle Scripts > gradle.scripts(module) 并在其中添加以下依赖项

implementation 'org.jsoup:jsoup:1.10.2'

步骤 3. 添加 Internet 权限

导航到 AndroidManifest.xml 文件并向其添加以下权限-

步骤 4. 处理 XML 文件

导航到 app > res > layout > activity_main.xml 并将以下代码添加到该文件。下面是 activity_main.xml 文件的代码。

XML


  
    
    
    
    
    
    
  


Java
package com.example.updatealertdialog;
  
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
  
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;
  
import org.jsoup.Jsoup;
  
import java.io.IOException;
  
public class MainActivity extends AppCompatActivity {
  
    // Initialize variables
    TextView tvCurrentVersion,tvLatestVersion;
    String sCurrentVersion,sLatestVersion;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Assign variables
        tvCurrentVersion=findViewById(R.id.tv_current_version);
        tvLatestVersion=findViewById(R.id.tv_latest_version);
  
        // Get latest version from play store
        new GetLatestVersion().execute();
    }
  
    private class GetLatestVersion extends AsyncTask {
  
        @Override
        protected String doInBackground(String... strings) {
            try {
                sLatestVersion= Jsoup
                        .connect("https://play.google.com//store/apps/details?id="
                        +getPackageName())
                        .timeout(30000)
                        .get()
                        .select("div.hAyfc:nth-child(4)>"+
                                "span:nth-child(2) > div:nth-child(1)"+
                                "> span:nth-child(1)")
                        .first()
                        .ownText();
            } catch (IOException e) {
                e.printStackTrace();
            }
  
            return sLatestVersion;
        }
  
        @Override
        protected void onPostExecute(String s) {
            // Get current version
            sCurrentVersion=BuildConfig.VERSION_NAME;
            // Set current version on Text view
            tvCurrentVersion.setText(sCurrentVersion);
            // Set latest version on TextView
            tvLatestVersion.setText(sLatestVersion);
  
            if(sLatestVersion != null)
            {
                // Version convert to float
                float cVersion=Float.parseFloat(sCurrentVersion);
                float lVersion=Float.parseFloat(sLatestVersion);
  
                // Check condition(latest version is
                  // greater than the current version)
                if(lVersion > cVersion)
                {
                    // Create update AlertDialog
                    updateAlertDialog();
                }
            }
        }
    }
  
    private void updateAlertDialog() {
        // Initialize AlertDialog
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        // Set title
        builder.setTitle(getResources().getString(R.string.app_name));
        // set message
        builder.setMessage("UUpdate Available");
        // Set non cancelable
        builder.setCancelable(false);
  
        // On update
        builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // Open play store
                startActivity(new Intent(Intent .ACTION_VIEW,
                        Uri.parse("market://details?id"+getPackageName())));
                // Dismiss alert dialog
                dialogInterface.dismiss();
            }
        });
  
        // on cancel
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // cancel alert dialog
                dialogInterface.cancel();
            }
        });
  
        // show alert dialog
        builder.show();
    }
}


步骤 5. 处理Java文件

导航到 MainActivity。 Java文件并在其中使用以下代码。代码中添加了注释以便更好地理解。

Java

package com.example.updatealertdialog;
  
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
  
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;
  
import org.jsoup.Jsoup;
  
import java.io.IOException;
  
public class MainActivity extends AppCompatActivity {
  
    // Initialize variables
    TextView tvCurrentVersion,tvLatestVersion;
    String sCurrentVersion,sLatestVersion;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Assign variables
        tvCurrentVersion=findViewById(R.id.tv_current_version);
        tvLatestVersion=findViewById(R.id.tv_latest_version);
  
        // Get latest version from play store
        new GetLatestVersion().execute();
    }
  
    private class GetLatestVersion extends AsyncTask {
  
        @Override
        protected String doInBackground(String... strings) {
            try {
                sLatestVersion= Jsoup
                        .connect("https://play.google.com//store/apps/details?id="
                        +getPackageName())
                        .timeout(30000)
                        .get()
                        .select("div.hAyfc:nth-child(4)>"+
                                "span:nth-child(2) > div:nth-child(1)"+
                                "> span:nth-child(1)")
                        .first()
                        .ownText();
            } catch (IOException e) {
                e.printStackTrace();
            }
  
            return sLatestVersion;
        }
  
        @Override
        protected void onPostExecute(String s) {
            // Get current version
            sCurrentVersion=BuildConfig.VERSION_NAME;
            // Set current version on Text view
            tvCurrentVersion.setText(sCurrentVersion);
            // Set latest version on TextView
            tvLatestVersion.setText(sLatestVersion);
  
            if(sLatestVersion != null)
            {
                // Version convert to float
                float cVersion=Float.parseFloat(sCurrentVersion);
                float lVersion=Float.parseFloat(sLatestVersion);
  
                // Check condition(latest version is
                  // greater than the current version)
                if(lVersion > cVersion)
                {
                    // Create update AlertDialog
                    updateAlertDialog();
                }
            }
        }
    }
  
    private void updateAlertDialog() {
        // Initialize AlertDialog
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        // Set title
        builder.setTitle(getResources().getString(R.string.app_name));
        // set message
        builder.setMessage("UUpdate Available");
        // Set non cancelable
        builder.setCancelable(false);
  
        // On update
        builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // Open play store
                startActivity(new Intent(Intent .ACTION_VIEW,
                        Uri.parse("market://details?id"+getPackageName())));
                // Dismiss alert dialog
                dialogInterface.dismiss();
            }
        });
  
        // on cancel
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // cancel alert dialog
                dialogInterface.cancel();
            }
        });
  
        // show alert dialog
        builder.show();
    }
}

这是我们应用程序的最终输出。

输出: