Tôi hiện đang phát triển một ứng dụng Android. Tôi cần làm gì đó khi ứng dụng được khởi chạy lần đầu tiên, tức là mã chỉ chạy trong lần đầu tiên chương trình được khởi chạy.
Tôi hiện đang phát triển một ứng dụng Android. Tôi cần làm gì đó khi ứng dụng được khởi chạy lần đầu tiên, tức là mã chỉ chạy trong lần đầu tiên chương trình được khởi chạy.
Câu trả lời:
Một ý tưởng khác là sử dụng cài đặt trong Tùy chọn chia sẻ. Ý tưởng chung giống như kiểm tra tệp trống, nhưng sau đó bạn không có tệp trống nào trôi nổi, không được sử dụng để lưu trữ bất kỳ thứ gì
Bạn có thể sử dụng SharedPreferences để xác định xem đó có phải là "Lần đầu tiên" ứng dụng được khởi chạy hay không. Chỉ cần sử dụng một biến Boolean ("my_first_time") và thay đổi giá trị của nó thành false khi nhiệm vụ của bạn "lần đầu tiên" kết thúc.
Đây là mã của tôi để nắm bắt lần đầu tiên bạn mở ứng dụng:
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();
}
Tôi đề nghị không chỉ lưu trữ cờ boolean mà còn cả mã phiên bản hoàn chỉnh. Bằng cách này, bạn cũng có thể truy vấn ngay từ đầu nếu đó là lần khởi động đầu tiên trong phiên bản mới. Ví dụ: bạn có thể sử dụng thông tin này để hiển thị hộp thoại "Whats mới".
Đoạn mã sau sẽ hoạt động từ bất kỳ lớp android nào "là ngữ cảnh" (các hoạt động, dịch vụ, ...). Nếu bạn muốn có nó trong một lớp (POJO) riêng biệt, bạn có thể cân nhắc sử dụng "ngữ cảnh tĩnh", chẳng hạn như được mô tả ở đây .
/**
* 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;
}
}
Nó có thể được sử dụng từ một hoạt động như thế này:
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;
}
// ...
}
// ...
}
Logic cơ bản có thể được xác minh bằng cách sử dụng thử nghiệm JUnit này:
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));
}
Với một chút nỗ lực hơn nữa, bạn có thể có thể kiểm tra những thứ liên quan đến android (PackageManager và SharedPreferences). Có ai quan tâm đến việc viết bài kiểm tra không? :)
Lưu ý rằng đoạn mã trên sẽ chỉ hoạt động bình thường nếu bạn không làm phiền với android:versionCodeAndroidManifest.xml của mình!
public AppStart checkAppStart(Context context, SharedPreferences sharedPreferences)là một chữ ký phương pháp tốt hơn nhiều
checkAppStartkhối đầu tiên . vì vậy tôi quyết định chia sẻ mã đã cập nhật của mình và xem liệu có ai có gợi ý về nó không
AppStarttừ các hoạt động khác nhau. Vì vậy, tôi đặt logic trong một phương pháp dịch vụ riêng biệt. Đó là lý do tại sao có một contextbiến và AppStartđược lưu trữ trong một biến tĩnh để tạo điều kiện cho các cuộc gọi phương thức Idempotent.
Tôi đã giải quyết để xác định xem ứng dụng có phải là lần đầu tiên của bạn hay không, tùy thuộc vào việc nó có phải là bản cập nhật hay không.
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
}
}
}
Tính toán kết quả:
Bạn có thể sử dụng Android SharedPreferences .
Android SharedPreferences cho phép chúng tôi lưu trữ dữ liệu ứng dụng nguyên thủy riêng tư dưới dạng cặp khóa-giá trị.
CODE
Tạo một lớp tùy chỉnh 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;
}
}
Bây giờ hãy mở Hoạt động của bạn & Khởi tạo .
private SharedPreference sharedPreferenceObj; // Declare Global
Bây giờ hãy gọi cái này trong phần OnCreate
sharedPreferenceObj=new SharedPreference(YourActivity.this);
Đang kiểm tra
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
}
Đây là một số mã cho việc này -
String path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Android/data/myapp/files/myfile.txt";
boolean exists = (new File(path)).exists();
if (!exists) {
doSomething();
}
else {
doSomethingElse();
}
Bạn có thể chỉ cần kiểm tra sự tồn tại của một tệp trống, nếu nó không tồn tại, sau đó thực thi mã của bạn và tạo tệp.
ví dụ
if(File.Exists("emptyfile"){
//Your code here
File.Create("emptyfile");
}
Tôi đã tạo một lớp đơn giản để kiểm tra xem mã của bạn có đang chạy lần đầu tiên không / n-lần!
Thí dụ
Tạo một sở thích riêng
FirstTimePreference prefFirstTime = new FirstTimePreference(getApplicationContext());
Sử dụng runTheFirstTime, chọn một khóa để kiểm tra sự kiện của bạn
if (prefFirstTime.runTheFirstTime("myKey")) {
Toast.makeText(this, "Test myKey & coutdown: " + prefFirstTime.getCountDown("myKey"),
Toast.LENGTH_LONG).show();
}
Sử dụng runTheFirstNTimes, chọn một khóa và thực thi bao nhiêu lần
if(prefFirstTime.runTheFirstNTimes("anotherKey" , 5)) {
Toast.makeText(this, "ciccia Test coutdown: "+ prefFirstTime.getCountDown("anotherKey"),
Toast.LENGTH_LONG).show();
}
Chỉ hỗ trợ điều này trong bản sửa đổi thư viện hỗ trợ 23.3.0 (trong phiên bản v4 có nghĩa là khả năng tương thích trở lại Android 1.6).
Trong hoạt động Trình khởi chạy của bạn, trước tiên hãy gọi:
AppLaunchChecker.onActivityCreate(activity);
Sau đó gọi:
AppLaunchChecker.hasStartedFromLauncher(activity);
Điều này sẽ trở lại nếu đây là lần đầu tiên ứng dụng được khởi chạy.
Nếu bạn đang tìm kiếm một cách đơn giản, đây là nó.
Tạo một lớp tiện ích như thế này,
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);
}
}
Tại Hoạt động chính của bạn, onCreate ()
if(!ApplicationUtils.getBooleanPreferenceValue(this,"isFirstTimeExecution")){
Log.d(TAG, "First time Execution");
ApplicationUtils.setBooleanPreferenceValue(this,"isFirstTimeExecution",true);
// do your first time execution stuff here,
}
cho 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();
}
Tại sao không sử dụng Trình trợ giúp cơ sở dữ liệu? Điều này sẽ có một onCreate tuyệt vời chỉ được gọi là lần đầu tiên ứng dụng được khởi động. Điều này sẽ giúp những người muốn theo dõi điều này sau khi ứng dụng ban đầu đã được cài đặt mà không cần theo dõi.
onCreate()được gọi cho mọi phiên bản mới. Ngoài ra, nó sẽ không được coi là thừa hoặc sử dụng một cái gì đó cho mục đích ngoài ý muốn?
Tôi muốn có "số lượng cập nhật" trong tùy chọn được chia sẻ của mình. Nếu nó không ở đó (hoặc giá trị 0 mặc định) thì đây là "lần sử dụng đầu tiên" ứng dụng của tôi.
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);
Vì vậy, bây giờ, bất cứ khi nào có bản cập nhật cho ứng dụng mà người dùng nên biết, tôi tăng 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);
Xin chào các bạn, tôi đang làm một việc như thế này. Và nó hoạt động với tôi
tạo trường Boolean trong tùy chọn chia sẻ. Giá trị mặc định là true {isFirstTime: true} sau lần đầu tiên đặt nó thành false. Không có gì có thể đơn giản và đáng tin cậy hơn điều này trong hệ thống Android.
Context.getSharedPreferences()đó sẽ kết thúc ở cùng một nơi, ngoại trừ nó sẽ hoạt động ở mọi nơi