응용 프로그램이 처음 실행 중인지 확인
이 질문에 이미 답변이 있습니다.
- 안드로이드 앱이 처음 사용되었는지 확인 14 답변
저는 안드로이드 개발이 처음이고 설치 후 처음 실행되는 응용 프로그램을 기반으로 응용 프로그램의 일부 속성을 설정하고 싶습니다. 응용 프로그램이 처음으로 실행되고 있음을 찾은 다음 첫 번째 실행 속성을 설정하는 방법이 있습니까?
다음은 SharedPreferences
'첫 실행'검사를 수행하기 위해 사용하는 예입니다 .
public class MyActivity extends Activity {
SharedPreferences prefs = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Perhaps set content view here
prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firstrun", false).commit();
}
}
}
"firstrun"키로 저장된 파일 prefs.getBoolean(...)
이없는 경우 코드가 실행 되면 앱이 실행 된 적이 없음을 나타냅니다. 해당 키로 부울을 저장 한 적이 없거나 사용자가 강제로 앱 데이터를 지 웠기 때문입니다. '첫 실행'시나리오). 이것이 첫 번째 실행이 아니면 행 이 실행 된 것이므로 두 번째 매개 변수로 제공된 기본 true를 대체 하므로 실제로 false를 리턴합니다.boolean
SharedPreferences
prefs.edit().putBoolean("firstrun", false).commit();
prefs.getBoolean("firstrun", true)
허용되는 대답은 첫 번째 실행과 후속 업그레이드를 구분하지 않습니다. 공유 환경 설정에서 부울을 설정하는 것만으로 앱이 처음 설치된 후 처음 실행되는지 여부 만 알려줍니다. 나중에 앱을 업그레이드하고 해당 업그레이드를 처음 실행할 때 일부를 변경하려는 경우 공유 환경 설정이 업그레이드간에 저장되기 때문에 더 이상 해당 부울을 사용할 수 없습니다.
이 메소드는 공유 환경 설정을 사용하여 부울이 아닌 버전 코드를 저장합니다.
import com.yourpackage.BuildConfig;
...
private void checkFirstRun() {
final String PREFS_NAME = "MyPrefsFile";
final String PREF_VERSION_CODE_KEY = "version_code";
final int DOESNT_EXIST = -1;
// Get current version code
int currentVersionCode = BuildConfig.VERSION_CODE;
// Get saved version code
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
int savedVersionCode = 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
앱이 시작될 때마다 확인되도록 기본 활동 에서이 메서드를 호출 할 수 있습니다.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkFirstRun();
}
private void checkFirstRun() {
// ...
}
}
필요한 경우 사용자가 이전에 설치 한 버전에 따라 특정 작업을 수행하도록 코드를 조정할 수 있습니다.
이 답변 에서 아이디어가 나왔습니다 . 이것 또한 도움이됩니다 :
- How can you get the Manifest Version number from the App's (Layout) XML variables?
- User versionName value of AndroidManifest.xml in code
If you are having trouble getting the version code, see the following Q&A:
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()) {
launchFlag = true;
writeInstallationFile(installation);
}
sID = readInstallationFile(installation);
} 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);
There is no way to know that through the Android API. You have to store some flag by yourself and make it persist either in a SharedPreferenceEditor
or using a database.
If you want to base some licence related stuff on this flag, I suggest you use an obfuscated preference editor provided by the LVL library. It's simple and clean.
Regards, Stephane
Just check for some preference with default value indicating that it's a first run. So if you get default value, do your initialization and set this preference to different value to indicate that the app is initialized already.
The following is an example of using SharedPreferences to achieve a 'forWhat' check.
preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferencesEditor = preferences.edit();
public static boolean isFirstRun(String forWhat) {
if (preferences.getBoolean(forWhat, true)) {
preferencesEditor.putBoolean(forWhat, false).commit();
return true;
} else {
return false;
}
}
There's no reliable way to detect first run, as the shared preferences way is not always safe, the user can delete the shared preferences data from the settings! a better way is to use the answers here Is there a unique Android device ID? to get the device's unique ID and store it somewhere in your server, so whenever the user launches the app you request the server and check if it's there in your database or it is new.
I'm not sure it's good way to check it. What about case when user uses button "clear data" from settings? SharedPreferences will be cleared and you catch "first run" again. And it's a problem. I guess it's better idea to use InstallReferrerReceiver.
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
// here you can launch another activity if you like
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference
}
}
This might help you
public class FirstActivity extends Activity {
SharedPreferences sharedPreferences = null;
Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedPreferences = getSharedPreferences("com.myAppName", MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
if (sharedPreferences.getBoolean("firstRun", true)) {
//You can perform anything over here. This will call only first time
editor = sharedPreferences.edit();
editor.putBoolean("firstRun", false)
editor.commit();
}
}
}
참고URL : https://stackoverflow.com/questions/7217578/check-if-application-is-on-its-first-run
'IT박스' 카테고리의 다른 글
페이지로드시 HTML 입력 상자에 초점 설정 (0) | 2020.08.31 |
---|---|
문자열을 HTML 인코딩 / 이스케이프하는 방법은 무엇입니까? (0) | 2020.08.31 |
원격 연결 Mysql Ubuntu (0) | 2020.08.31 |
안드로이드 디자인 지원 TabLayout에서 탭 텍스트의 글꼴 변경 (0) | 2020.08.31 |
이벤트 처리기가 두 번 연결되는 것을 방지하는 C # 패턴 (0) | 2020.08.31 |