ฉันกำลังพัฒนาแอพ Android ฉันต้องทำอะไรบางอย่างเมื่อเปิดตัวแอปเป็นครั้งแรกนั่นคือโค้ดจะทำงานในครั้งแรกที่เปิดตัวโปรแกรมเท่านั้น
ฉันกำลังพัฒนาแอพ Android ฉันต้องทำอะไรบางอย่างเมื่อเปิดตัวแอปเป็นครั้งแรกนั่นคือโค้ดจะทำงานในครั้งแรกที่เปิดตัวโปรแกรมเท่านั้น
คำตอบ:
อีกแนวคิดหนึ่งคือการใช้การตั้งค่าใน Shared Preferences แนวคิดทั่วไปเหมือนกับการตรวจสอบไฟล์ว่าง แต่คุณไม่มีไฟล์ว่างลอยอยู่รอบ ๆ ไม่ได้ใช้เพื่อจัดเก็บอะไรเลย
คุณสามารถใช้SharedPreferencesเพื่อระบุว่าเป็น "ครั้งแรก" ที่เปิดตัวแอปหรือไม่ เพียงใช้ตัวแปรบูลีน ("my_first_time") และเปลี่ยนค่าเป็นเท็จเมื่องาน "ครั้งแรก" ของคุณสิ้นสุดลง
นี่คือรหัสของฉันที่ใช้จับในครั้งแรกที่คุณเปิดแอป:
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
//the app is being launched for first time, do something
Log.d("Comments", "First time");
// first time task
// record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).commit();
}
ฉันขอแนะนำให้ไม่เพียงเก็บแฟล็กบูลีนเท่านั้น แต่ยังต้องระบุโค้ดเวอร์ชันที่สมบูรณ์ด้วย ด้วยวิธีนี้คุณสามารถสอบถามได้ในตอนต้นหากเป็นการเริ่มต้นครั้งแรกในเวอร์ชันใหม่ คุณสามารถใช้ข้อมูลนี้เพื่อแสดงกล่องโต้ตอบ "มีอะไรใหม่" ได้เช่น
โค้ดต่อไปนี้ควรใช้งานได้จากคลาส Android ที่ "เป็นบริบท" (กิจกรรมบริการ ... ) หากคุณต้องการที่จะมีมันในการแยก (POJO) ระดับคุณสามารถพิจารณาใช้ "บริบทคงที่" ตามที่อธิบายไว้ที่นี่เช่น
/**
* Distinguishes different kinds of app starts: <li>
* <ul>
* First start ever ({@link #FIRST_TIME})
* </ul>
* <ul>
* First start in this version ({@link #FIRST_TIME_VERSION})
* </ul>
* <ul>
* Normal app start ({@link #NORMAL})
* </ul>
*
* @author schnatterer
*
*/
public enum AppStart {
FIRST_TIME, FIRST_TIME_VERSION, NORMAL;
}
/**
* The app version code (not the version name!) that was used on the last
* start of the app.
*/
private static final String LAST_APP_VERSION = "last_app_version";
/**
* Finds out started for the first time (ever or in the current version).<br/>
* <br/>
* Note: This method is <b>not idempotent</b> only the first call will
* determine the proper result. Any subsequent calls will only return
* {@link AppStart#NORMAL} until the app is started again. So you might want
* to consider caching the result!
*
* @return the type of app start
*/
public AppStart checkAppStart() {
PackageInfo pInfo;
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
AppStart appStart = AppStart.NORMAL;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
int lastVersionCode = sharedPreferences
.getInt(LAST_APP_VERSION, -1);
int currentVersionCode = pInfo.versionCode;
appStart = checkAppStart(currentVersionCode, lastVersionCode);
// Update version in preferences
sharedPreferences.edit()
.putInt(LAST_APP_VERSION, currentVersionCode).commit();
} catch (NameNotFoundException e) {
Log.w(Constants.LOG,
"Unable to determine current app version from pacakge manager. Defenisvely assuming normal app start.");
}
return appStart;
}
public AppStart checkAppStart(int currentVersionCode, int lastVersionCode) {
if (lastVersionCode == -1) {
return AppStart.FIRST_TIME;
} else if (lastVersionCode < currentVersionCode) {
return AppStart.FIRST_TIME_VERSION;
} else if (lastVersionCode > currentVersionCode) {
Log.w(Constants.LOG, "Current version code (" + currentVersionCode
+ ") is less then the one recognized on last startup ("
+ lastVersionCode
+ "). Defenisvely assuming normal app start.");
return AppStart.NORMAL;
} else {
return AppStart.NORMAL;
}
}
สามารถใช้จากกิจกรรมเช่นนี้:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
switch (checkAppStart()) {
case NORMAL:
// We don't want to get on the user's nerves
break;
case FIRST_TIME_VERSION:
// TODO show what's new
break;
case FIRST_TIME:
// TODO show a tutorial
break;
default:
break;
}
// ...
}
// ...
}
ตรรกะพื้นฐานสามารถตรวจสอบได้โดยใช้การทดสอบ JUnit นี้:
public void testCheckAppStart() {
// First start
int oldVersion = -1;
int newVersion = 1;
assertEquals("Unexpected result", AppStart.FIRST_TIME,
service.checkAppStart(newVersion, oldVersion));
// First start this version
oldVersion = 1;
newVersion = 2;
assertEquals("Unexpected result", AppStart.FIRST_TIME_VERSION,
service.checkAppStart(newVersion, oldVersion));
// Normal start
oldVersion = 2;
newVersion = 2;
assertEquals("Unexpected result", AppStart.NORMAL,
service.checkAppStart(newVersion, oldVersion));
}
ด้วยความพยายามอีกเล็กน้อยคุณอาจทดสอบสิ่งที่เกี่ยวข้องกับ Android (PackageManager และ SharedPreferences) ได้เช่นกัน ทุกคนที่สนใจในการเขียนการทดสอบ? :)
โปรดทราบว่าโค้ดด้านบนจะทำงานได้อย่างถูกต้องก็ต่อเมื่อคุณไม่ยุ่งกับของคุณandroid:versionCodeใน AndroidManifest.xml!
public AppStart checkAppStart(Context context, SharedPreferences sharedPreferences)เป็นลายเซ็นวิธีการที่ดีกว่ามาก
checkAppStartบล็อกแรก ดังนั้นฉันจึงตัดสินใจแบ่งปันรหัสที่อัปเดตของฉันและดูว่าใครมีข้อเสนอแนะเกี่ยวกับเรื่องนี้
AppStartจากกิจกรรมต่างๆ ดังนั้นฉันจึงใส่ตรรกะในวิธีการบริการแยกต่างหาก นั่นเป็นเหตุผลที่มีcontextตัวแปรและAppStartถูกเก็บไว้ในตัวแปรคงที่เพื่ออำนวยความสะดวกในการเรียกเมธอด idempotent
ฉันแก้ไขเพื่อตรวจสอบว่าแอปพลิเคชันเป็นครั้งแรกของคุณหรือไม่ขึ้นอยู่กับว่าเป็นการอัปเดต
private int appGetFirstTimeRun() {
//Check if App Start First Time
SharedPreferences appPreferences = getSharedPreferences("MyAPP", 0);
int appCurrentBuildVersion = BuildConfig.VERSION_CODE;
int appLastBuildVersion = appPreferences.getInt("app_first_time", 0);
//Log.d("appPreferences", "app_first_time = " + appLastBuildVersion);
if (appLastBuildVersion == appCurrentBuildVersion ) {
return 1; //ya has iniciado la appp alguna vez
} else {
appPreferences.edit().putInt("app_first_time",
appCurrentBuildVersion).apply();
if (appLastBuildVersion == 0) {
return 0; //es la primera vez
} else {
return 2; //es una versión nueva
}
}
}
ผลการคำนวณ:
คุณสามารถใช้SharedPreferences Android
Android SharedPreferences ช่วยให้เราสามารถจัดเก็บข้อมูลแอปพลิเคชันดั้งเดิมส่วนตัวในรูปแบบของคู่คีย์ - ค่า
รหัส
สร้างคลาสที่กำหนดเองSharedPreference
public class SharedPreference {
android.content.SharedPreferences pref;
android.content.SharedPreferences.Editor editor;
Context _context;
private static final String PREF_NAME = "testing";
// All Shared Preferences Keys Declare as #public
public static final String KEY_SET_APP_RUN_FIRST_TIME = "KEY_SET_APP_RUN_FIRST_TIME";
public SharedPreference(Context context) // Constructor
{
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
/*
* Set Method Generally Store Data;
* Get Method Generally Retrieve Data ;
* */
public void setApp_runFirst(String App_runFirst)
{
editor.remove(KEY_SET_APP_RUN_FIRST_TIME);
editor.putString(KEY_SET_APP_RUN_FIRST_TIME, App_runFirst);
editor.apply();
}
public String getApp_runFirst()
{
String App_runFirst= pref.getString(KEY_SET_APP_RUN_FIRST_TIME, "FIRST");
return App_runFirst;
}
}
ตอนนี้เปิดของคุณกิจกรรมและการเริ่มต้น
private SharedPreference sharedPreferenceObj; // Declare Global
ตอนนี้เรียกสิ่งนี้ในส่วนOnCreate
sharedPreferenceObj=new SharedPreference(YourActivity.this);
กำลังตรวจสอบ
if(sharedPreferenceObj.getApp_runFirst().equals("FIRST"))
{
// That's mean First Time Launch
// After your Work , SET Status NO
sharedPreferenceObj.setApp_runFirst("NO");
}
else
{
// App is not First Time Launch
}
นี่คือรหัสบางส่วนสำหรับสิ่งนี้ -
String path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Android/data/myapp/files/myfile.txt";
boolean exists = (new File(path)).exists();
if (!exists) {
doSomething();
}
else {
doSomethingElse();
}
มีการสนับสนุนสิ่งนี้ในการแก้ไขไลบรารีการสนับสนุน 23.3.0 (ใน v4 ซึ่งหมายถึงความสามารถในการกลับไปใช้ Android 1.6)
ในกิจกรรม Launcher ของคุณโทรครั้งแรก:
AppLaunchChecker.onActivityCreate(activity);
จากนั้นโทร:
AppLaunchChecker.hasStartedFromLauncher(activity);
ซึ่งจะกลับมาหากนี่เป็นครั้งแรกที่เปิดตัวแอป
คุณสามารถตรวจสอบการมีอยู่ของไฟล์ว่างหากไม่มีอยู่ให้รันโค้ดของคุณและสร้างไฟล์
เช่น
if(File.Exists("emptyfile"){
//Your code here
File.Create("emptyfile");
}
ฉันสร้างคลาสง่ายๆเพื่อตรวจสอบว่าโค้ดของคุณทำงานเป็นครั้งแรกหรือไม่ / n-times!
ตัวอย่าง
สร้างความชอบที่ไม่เหมือนใคร
FirstTimePreference prefFirstTime = new FirstTimePreference(getApplicationContext());
ใช้ runTheFirstTime เลือกคีย์เพื่อตรวจสอบเหตุการณ์ของคุณ
if (prefFirstTime.runTheFirstTime("myKey")) {
Toast.makeText(this, "Test myKey & coutdown: " + prefFirstTime.getCountDown("myKey"),
Toast.LENGTH_LONG).show();
}
ใช้ runTheFirstNTimes เลือกคีย์และจำนวนครั้งที่ดำเนินการ
if(prefFirstTime.runTheFirstNTimes("anotherKey" , 5)) {
Toast.makeText(this, "ciccia Test coutdown: "+ prefFirstTime.getCountDown("anotherKey"),
Toast.LENGTH_LONG).show();
}
หากคุณกำลังมองหาวิธีง่ายๆนี่คือ
สร้างคลาสยูทิลิตี้เช่นนี้
public class ApplicationUtils {
/**
* Sets the boolean preference value
*
* @param context the current context
* @param key the preference key
* @param value the value to be set
*/
public static void setBooleanPreferenceValue(Context context, String key, boolean value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean(key, value).apply();
}
/**
* Get the boolean preference value from the SharedPreference
*
* @param context the current context
* @param key the preference key
* @return the the preference value
*/
public static boolean getBooleanPreferenceValue(Context context, String key) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(key, false);
}
}
ที่กิจกรรมหลักของคุณ onCreate ()
if(!ApplicationUtils.getBooleanPreferenceValue(this,"isFirstTimeExecution")){
Log.d(TAG, "First time Execution");
ApplicationUtils.setBooleanPreferenceValue(this,"isFirstTimeExecution",true);
// do your first time execution stuff here,
}
สำหรับ kotlin
fun checkFirstRun() {
var prefs_name = "MyPrefsFile"
var pref_version_code_key = "version_code"
var doesnt_exist: Int = -1;
// Get current version code
var currentVersionCode = BuildConfig.VERSION_CODE
// Get saved version code
var prefs: SharedPreferences = getSharedPreferences(prefs_name, MODE_PRIVATE)
var savedVersionCode: Int = prefs.getInt(pref_version_code_key, doesnt_exist)
// Check for first run or upgrade
if (currentVersionCode == savedVersionCode) {
// This is just a normal run
return;
} else if (savedVersionCode == doesnt_exist) {
// TODO This is a new install (or the user cleared the shared preferences)
} else if (currentVersionCode > savedVersionCode) {
// TODO This is an upgrade
}
// Update the shared preferences with the current version code
prefs.edit().putInt(pref_version_code_key, currentVersionCode).apply();
}
ทำไมไม่ใช้ตัวช่วยฐานข้อมูล สิ่งนี้จะมี onCreate ที่ดีซึ่งเรียกว่าครั้งแรกที่เริ่มแอปเท่านั้น สิ่งนี้จะช่วยให้ผู้ที่ต้องการติดตามสิ่งนี้หลังจากที่มีการติดตั้งแอปเริ่มต้นโดยไม่มีการติดตาม
onCreate()มันถูกเรียกสำหรับเวอร์ชันใหม่ทุกครั้ง นอกจากนี้จะไม่ถือว่าฟุ่มเฟือยหรือใช้บางอย่างเพื่อวัตถุประสงค์ที่ไม่ได้ตั้งใจหรือไม่?
ฉันต้องการ "จำนวนการอัปเดต" ในค่ากำหนดที่ใช้ร่วมกันของฉัน หากไม่มี (หรือค่าศูนย์เริ่มต้น) นี่คือ "การใช้งานครั้งแรก" ของแอปของฉัน
private static final int UPDATE_COUNT = 1; // Increment this on major change
...
if (sp.getInt("updateCount", 0) == 0) {
// first use
} else if (sp.getInt("updateCount", 0) < UPDATE_COUNT) {
// Pop up dialog telling user about new features
}
...
sp.edit().putInt("updateCount", UPDATE_COUNT);
ตอนนี้เมื่อใดก็ตามที่มีการอัปเดตแอปที่ผู้ใช้ควรทราบฉันจะเพิ่ม UPDATE_COUNT
/**
* @author ALGO
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
import android.content.Context;
public class Util {
// ===========================================================
//
// ===========================================================
private static final String INSTALLATION = "INSTALLATION";
public synchronized static boolean isFirstLaunch(Context context) {
String sID = null;
boolean launchFlag = false;
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists()) {
writeInstallationFile(installation);
}
sID = readInstallationFile(installation);
launchFlag = true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return launchFlag;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");// read only mode
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
> Usage (in class extending android.app.Activity)
Util.isFirstLaunch(this);
สวัสดีครับผมกำลังทำอะไรแบบนี้ และมันใช้ได้ผลสำหรับฉัน
สร้างฟิลด์บูลีนในการกำหนดค่าตามความชอบที่ใช้ร่วมกันค่าเริ่มต้นเป็นจริง {isFirstTime: true} หลังจากครั้งแรกตั้งค่าเป็นเท็จ ไม่มีอะไรจะง่ายและน่าเชื่อถือไปกว่านี้ในระบบ Android
Context.getSharedPreferences()มันจะจบลงในที่เดียวกันยกเว้นว่าจะใช้ได้ทุกที่