【安卓】判断"全新安装初次打开、升级后初次打开、第二次打开",比如可用于判断是否应显示"引导页"、!

思路:

1.基于SharedPreferences,每次打开时,根据上次打开时记录的版本即可区分此次打开的情形。



StoredData.java:

1.Application.onCreate中调用StoredData.getThis().markOpenApp();即可。其他位置就可以根据getLaunchMode判断打开类型了。

package com.example.test;

import android.app.Application;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

public class StoredData {

	public static final int LMODE_NEW_INSTALL = 1; // 启动-模式,首次安装-首次启动、覆盖安装-首次启动、已安装-二次启动
	public static final int LMODE_UPDATE = 2;
	public static final int LMODE_AGAIN = 3;

	private boolean isOpenMarked = false;
	private int launchMode = LMODE_AGAIN; // 启动-模式

	private static StoredData instance;

	private SharedPreferences share; // 一般信息

	public static StoredData getThis() {
		if (instance == null)
			instance = new StoredData();

		return instance;
	}

	// -------启动状态------------------------------------------------------------

	// 标记-打开app,用于产生-是否首次打开
	public void markOpenApp() {
		// 防止-重复调用
		if (isOpenMarked)
			return;
		isOpenMarked = true;

		String lastVersion = share.getString("lastVersion", "");
		String thisVersion = getAppVersion();

		// 首次启动
		if (TextUtils.isEmpty(lastVersion)) {
			launchMode = LMODE_NEW_INSTALL;
			share.edit().putString("lastVersion", thisVersion).commit();
		}
		// 更新
		else if (!thisVersion.equals(lastVersion)) {
			launchMode = LMODE_UPDATE;
			share.edit().putString("lastVersion", thisVersion).commit();
		}
		// 二次启动(版本未变)
		else
			launchMode = LMODE_AGAIN;
	}

	public int getLaunchMode() {
		return launchMode;
	}

	// 首次打开,新安装、覆盖(版本号不同)
	public boolean isFirstOpen() {
		return launchMode != LMODE_AGAIN;
	}

	// -------------------------
	// 软件-版本
	public static String getAppVersion() {

		String versionName = "";
		Application app = MyApplication.getThis();
		try {
			PackageManager pkgMng = app.getPackageManager();
			PackageInfo pkgInfo = pkgMng
					.getPackageInfo(app.getPackageName(), 0);
			versionName = pkgInfo.versionName;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		return versionName;
	}
}


  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值