13

我在市场上有一个 android 应用程序,我注意到当我发布新版本时更新应用程序可能需要相当长的时间。

我希望类似于谷歌使用他们的谷歌浏览器应用程序所做的事情(可能只是测试版,它不确定)。

我想要做的是当用户启动我的应用程序时,它可以检查是否有新版本可用,如果有,只需在底部显示一条小消息以通知用户有新版本可供下载。如果他们点击它,那么用户将被直接带到 Play 商店中的应用程序,以便他们可以开始更新。

这是怎么做到的?我没有找到任何适用于 android 的东西,我发现了一些与 iOS 相关的东西,但显然对我没有好处。

感谢您的任何帮助,您可以提供。

4

10 回答 10

17

当您可以通过 Google Play 检查您的应用程序的最新版本时,没有 API 或服务。

相反,你应该在你的服务器上维护最新的版本代码,并让你的应用定期检查它自己的版本代码。如果服务器上的版本代码更高,那么您的应用程序需要更新,您可以相应地告诉用户。

于 2013-05-09T16:32:41.163 回答
8

您可以使用这个新的 Android 官方 API https://developer.android.com/guide/app-bundle/in-app-updates

于 2019-06-25T17:00:57.507 回答
6

真诚地,我认为这根本不值得付出努力。我的第一个建议是忘记它,因为 Play 商店会处理更新通知。

如果您真的想投入时间和精力,请检查:

于 2013-05-09T16:48:27.547 回答
2

我是使用 Firebase 远程配置完成的。这是我的方法,被称为一次-

private void checkAndShowUpdateAvailableAlert() {
    try {
        String VERSION = "version";
        String NEW_FEATURES = "newFeatures";

        if (singleton.isUpdateAvailable()) {
            FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
            FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
                    .setDeveloperModeEnabled(BuildConfig.DEBUG)
                    .build();
            firebaseRemoteConfig.setConfigSettings(configSettings);

            Map<String, Object> defaultValueHashMap = new HashMap<>();
            defaultValueHashMap.put(VERSION, BuildConfig.VERSION_CODE);
            defaultValueHashMap.put(NEW_FEATURES, "");

            firebaseRemoteConfig.setDefaults(defaultValueHashMap);

            long cacheExpiration = 3600; // 1 hour in seconds.
            if (firebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) {
                cacheExpiration = 0;
            }

            firebaseRemoteConfig.fetch(cacheExpiration)
                    .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                // showing update alert only one time
                                singleton.setUpdateAvailable(false);

                                firebaseRemoteConfig.activateFetched();
                                long remoteVersionCode = firebaseRemoteConfig.getLong(VERSION);
                                String newFeatures = firebaseRemoteConfig.getString(NEW_FEATURES);
                                Log.d(TAG, "Remote version: " + remoteVersionCode
                                        + ", New Features: " + newFeatures);
                                if (remoteVersionCode > BuildConfig.VERSION_CODE
                                        && newFeatures != null
                                        && !newFeatures.isEmpty()) {
                                    contextUtility.showUpdateAlert(newFeatures);
                                }

                            } else {
                                Log.e(TAG, "Remote config fetch failed");
                            }
                        }
                    });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

脚步-

我在我的 firebase 项目中维护两个键值对-

1. newFeatures and 
2. version

version 实际上是 versionCode (integer),它与我最新的 build versionCode 同步。当我发布任何新版本时,我会从 firebase 控制台更新此值。

在应用程序中,我检查这个值(一次),如果它更大,我会向用户显示更新警报。newFeatures 是向用户显示的附加键what's new

检查完整的源代码 - https://github.com/varunon9/SaathMeTravel

于 2018-12-26T17:03:27.730 回答
2

它可能对其他人有用。我试过这种方式

首先创建一个具有几个方法的类来启动 Play 商店并以这种方式获取应用程序版本代码和版本信息

public class CheckForUpdate {

public static final String ACTION_APP_VERSION_CHECK="app-version-check";

public static void launchPlayStoreApp(Context context)
{

    final String appPackageName = context.getPackageName(); // getPackageName() from Context or Activity object
    try {
        context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
    } catch (android.content.ActivityNotFoundException anfe) {
        context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
    }

}

public static int getRemoteVersionNumber(Context context)
{
    int versionCode=0;
    try {
        PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        String version = pInfo.versionName;
        versionCode=pInfo.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return versionCode;
}

}

其次创建另一个具有 sharedpreference 方法的 util 类以这种方式保存和检索版本代码

public class PreferenceUtils {

// this is for version code
private  final String APP_VERSION_CODE = "APP_VERSION_CODE";
private  SharedPreferences sharedPreferencesAppVersionCode;
private SharedPreferences.Editor editorAppVersionCode;
private static Context mContext;

public PreferenceUtils(Context context)
{
    this.mContext=context;
    // this is for app versioncode
    sharedPreferencesAppVersionCode=mContext.getSharedPreferences(APP_VERSION_CODE,MODE_PRIVATE);
    editorAppVersionCode=sharedPreferencesAppVersionCode.edit();
}

public void createAppVersionCode(int versionCode) {

    editorAppVersionCode.putInt(APP_VERSION_CODE, versionCode);
    editorAppVersionCode.apply();
}

public int getAppVersionCode()
{
    return sharedPreferencesAppVersionCode.getInt(APP_VERSION_CODE,0); // as default version code is 0
}

}

最后,您可以在启动器活动或任何其他活动中使用您希望向用户显示警报对话框以更新应用程序(如果已更新)。

public class DashboardActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
   ...........
    //check whether app is first time launched
    AppLaunchChecker.onActivityCreate(this);
    alertAppUpdate();
}

以这种方式实现 alertAppUpdate() 方法

private void alertAppUpdate()
{

int remoteVersionCode=CheckForUpdate.getRemoteVersionNumber(this);
PreferenceUtils preferenceUtils=new PreferenceUtils(this);
if(AppLaunchChecker.hasStartedFromLauncher(this))
{
    preferenceUtils.createAppVersionCode(remoteVersionCode);
    Log.i("First time","First time app is launched");
}
int existingVersionCode= preferenceUtils.getAppVersionCode();
if(remoteVersionCode>existingVersionCode)
{
    /*
      **
      * app is updated, alert user to update app from playstore 
      * if app is updated then only save the version code in preferenceUtils
      *
     */


    AlertDialog.Builder dialogBuilder=AlertDialogBox.getAlertDialogBuilder(this,"Update available","Do you want to update your app now?");
    dialogBuilder.setPositiveButton("Update Now", (dialogInterface, i) -> {
        CheckForUpdate.launchPlayStoreApp(this);
        Log.i("app update service","app is needed to update");
        preferenceUtils.createAppVersionCode(remoteVersionCode);
    });
    dialogBuilder.setNegativeButton("Later",(dialogInterface,i)->{

    });    

    dialogBuilder.show();
    }
}

如果有任何错误,请告诉我。谢谢你。

于 2018-12-13T02:37:01.777 回答
1

您可以使用 google play 核心库来实现这一点。

首先,您需要将库包含在您的 gradle 依赖项中:

implementation "com.google.android.play:core-ktx:1.7.0"

然后你可以像这样使用它:

class InAppUpdateManager @Inject constructor(
    private val activity: Activity,
    private val delegate: InAppUpdateDelegate
) {

    private val appUpdateManager: AppUpdateManager by lazy {
        AppUpdateManagerFactory.create(activity)
    }

    fun checkForUpdates() {
        if (BuildConfig.IS_TEST_BACKEND) delegate.onUpdateNotAvailable()
        else this.requestUpdate()
    }

    private fun requestUpdate() {
        val updateStateListener = InstallStateUpdatedListener(delegate::onUpdatedStateChanged)
        appUpdateManager.registerListener(updateStateListener)

        appUpdateManager.appUpdateInfo
            .addOnFailureListener(delegate::onUpdateInstallError)
            .addOnSuccessListener(this::handleUpdateInfo)
    }

    private fun handleUpdateInfo(appUpdateInfo: AppUpdateInfo) {
        when (appUpdateInfo.updateAvailability()) {
            UpdateAvailability.UPDATE_AVAILABLE,
            UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS -> {
                delegate.onUpdateAvailable()
                this.startInAppUpdate(appUpdateInfo)
            }

            else -> {
                delegate.onUpdateNotAvailable()
            }
        }
    }

    private fun startInAppUpdate(appUpdateInfo: AppUpdateInfo) {
        val updateType = when {
            appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE) -> AppUpdateType.IMMEDIATE
            appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE) -> AppUpdateType.FLEXIBLE
            else -> null
        }

        if (updateType == null) {
            delegate.onInAppUpdateNotAllowed()
            return
        }

        appUpdateManager.startUpdateFlowForResult(
            appUpdateInfo,
            updateType,
            activity,
            REQUEST_CODE_UPDATE
        )
    }

    interface InAppUpdateDelegate {
        fun onUpdateAvailable()
        fun onInAppUpdateNotAllowed()
        fun onUpdateNotAvailable()
        fun onUpdatedStateChanged(installStatus: InstallState)
        fun onUpdateInstallError(error: Exception)
    }

    companion object {
        const val REQUEST_CODE_UPDATE = 69
    }
}

来源:https ://developer.android.com/guide/playcore/in-app-updates/kotlin-java

于 2021-03-30T20:50:59.440 回答
0

如何检查 Playstore 上是否有新版本的应用程序可用,通知用户在 android 中用新版本更新旧应用程序并显示是或否以获取他们的 Playstore。只需按照说明并将附加的代码放入您的应用程序中即可检查新版本的应用程序是否可用。此代码每天检查应用程序版本,如果 Playstore 上有任何新版本更新可用,则会在应用程序启动时出现一个弹出窗口以进行更新。

if (newVersion > curVersion) {
                    /* Post a Handler for the UI to pick up and open the Dialog */
                    mHandler.post(showUpdate);
                } 
   private Runnable showUpdate = new Runnable(){
           public void run(){
            new AlertDialog.Builder(MainActivity.this)
            .setIcon(R.drawable.ic_launcher)
            .setTitle("Update available")
            .setMessage("An update for Live Share Tips is available on Play Store.")
            .setNegativeButton("Update now", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                            /* User clicked OK so do some stuff */
                        easyTracker.send(MapBuilder.createEvent("App update",
                                "Update now", " ", null).build());
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.appuonline.livesharetips"));
                            startActivity(intent);
                    }
            })
            .setPositiveButton("Later", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                            /* User clicked Cancel */
                        easyTracker.send(MapBuilder.createEvent("Update_Later",
                                "Update later", " ", null).build());
                    }
            })
            .show();
           }
    }; 

下载完整代码[url]:http ://androidaone.com/11-2014/notify-users-update-app-new-version-available-playstore/

于 2014-12-26T12:25:09.587 回答
0

谷歌刚刚让这一切变得容易多了。见https://developer.android.com/guide/app-bundle/in-app-updates

于 2019-05-16T00:20:23.507 回答
0

我们使用的方法如下..

我将云(其中包含新的应用程序版本)发送到应用程序并在应用程序中处理它。在处理此云时,我会检查天气,我当前的版本和云中的版本与我定期向用户显示弹出窗口以从 Google Play 更新应用程序不同。

于 2018-05-10T10:02:29.187 回答
-1
    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
                    va = String.valueOf(packageInfo.getLongVersionCode());
                } else {
                    va = String.valueOf(packageInfo.versionCode);
                }
//get last version from server like below code and comparison whit va 
                sv = new serviceApi(this);
                sv.getVC("VERC_market", new setver.OnVC() {
                    @Override
                    public void onReceived(String vc) {
                        int vc1 = Integer.parseInt(vc);
                        int va1 = Integer.parseInt(va);
                        if (va1 < vc1) {
                            new AlertDialog.Builder(DemoPrimaryVocabGrouping.this)
                                    .setMessage("hi pls give last version ")
                                    .setPositiveButton("update", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent goToMarket = new Intent(Intent.ACTION_VIEW).setData(Uri
                                                    .parse("your app link in market"));
                                            startActivity(goToMarket);
                                        }
                               `enter code here`     })
                                    .setNegativeButton("no ", null)
                                    .setIcon(android.R.drawable.ic_dialog_alert)
                                    .show();
                        }
                    }
                });
于 2021-04-28T16:34:22.313 回答