현재 Android 앱을 개발 중입니다. 앱이 처음 실행될 때 뭔가를해야합니다. 즉, 프로그램이 처음 실행될 때만 코드가 실행됩니다.
현재 Android 앱을 개발 중입니다. 앱이 처음 실행될 때 뭔가를해야합니다. 즉, 프로그램이 처음 실행될 때만 코드가 실행됩니다.
답변:
또 다른 아이디어는 공유 기본 설정의 설정을 사용하는 것입니다. 빈 파일을 확인하는 것과 동일한 일반적인 아이디어이지만 아무것도 저장하는 데 사용되지 않는 빈 파일이 떠 다니지 않습니다.
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));
}
조금 더 노력하면 아마도 안드로이드 관련 항목 (PackageManager 및 SharedPreferences)도 테스트 할 수 있습니다. 시험 작성에 관심이있는 사람이 있습니까? :)
위의 코드는 android:versionCodeAndroidManifest.xml에서 엉망이되지 않는 경우에만 제대로 작동합니다 .
public AppStart checkAppStart(Context context, SharedPreferences sharedPreferences). 훨씬 더 나은 메서드 시그니처
checkAppStart블록 에서 다시 계산되지 않았기 때문에 내 연습 루프에 영원히 멈출 원래 코드에 문제가 있습니다. 그래서 난 내 업데이트 된 코드를 공유하고 누군가가 그것에 대해 제안이 있는지 결정
AppStart. 그래서 논리를 별도의 서비스 방법에 넣었습니다. 거기에 이유의 그 context변수와 AppStart나무 등 메서드 호출을 용이하게하기 위해 정적 변수에 저장되었다.
업데이트 여부에 따라 응용 프로그램이 처음인지 아닌지 확인하기 위해 해결했습니다.
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
}
}
}
계산 결과 :
Android SharedPreferences 를 사용할 수 있습니다 .
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();
}
빈 파일이 존재하지 않는지 확인한 다음 코드를 실행하고 파일을 생성하면됩니다.
예 :
if(File.Exists("emptyfile"){
//Your code here
File.Create("emptyfile");
}
코드가 처음 / n 번 실행되는지 확인하는 간단한 클래스를 만들었습니다!
예
고유 한 선호도 만들기
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();
}
지원 라이브러리 개정판 23.3.0 (v4에서는 Android 1.6으로의 호환성을 의미 함)에서 이에 대한 지원이 있습니다.
런처 활동에서 먼저 다음을 호출하십시오.
AppLaunchChecker.onActivityCreate(activity);
그런 다음 전화 :
AppLaunchChecker.hasStartedFromLauncher(activity);
앱이 처음 실행 된 경우 반환됩니다.
간단한 방법을 찾고 있다면 여기에 있습니다.
이와 같은 유틸리티 클래스를 만듭니다.
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,
}
코 틀린
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()모든 새로운 버전에 대해 호출됩니다. 또한 불필요한 것으로 간주되거나 의도하지 않은 목적으로 사용되지 않습니까?
내 공유 환경 설정에 "업데이트 횟수"가있는 것을 좋아합니다. 이것이 없으면 (또는 기본값 0 값) 내 앱의 "처음 사용"입니다.
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);
안녕하세요 여러분 저는 이런 일을하고 있습니다. 그리고 나를위한 작품
공유 환경 설정에서 Boolean 필드를 만듭니다. 처음으로 false로 설정 한 후 기본값은 true {isFirstTime : true}입니다. 안드로이드 시스템에서 이것보다 간단하고 신뢰할 수있는 것은 없습니다.
Context.getSharedPreferences()이 같은 장소에서 끝날 것, 그것은 어디에서나 작동 제외시켰다