How to know the last launch time of an app - android

Hi After doing lots of Search , I could not find the answer of a question, that seems somewhat simple.
I have multiple apps installed on device. Is there any way of finding the last launching date of all apps?

You could put the time and date in an SharedPref when the app opens.
Then, the next time you open the app the app reads the SharedPref and displays it.
Something like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar c = Calendar.getInstance();
SharedPreferences sp = this.getPreferences(Context.MODE_PRIVATE);
String lastLaunch = sp.getString("launch", "First launch!");
SharedPreferences.Editor editor = sp.edit();
editor.putString("launch", c.getTime().toString());
editor.commit();
}
The String lastLaunch is the last time it launched! If it's the first time the string is: "First launch!"
I hope that i have helped you a little bit :)

Based on your requirements from the comments above, I'm providing a method to share the launch times between a bunch of our apps using SharedPreferences.
Firstly, we need to allow our apps to share local storage so they can access preference data. For this, we use the sharedUserId property in the app manifest. This can be your own unique string and each of the apps that share the space must have this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.com.myapp"
android:sharedUserId="string.user.id.here">
...
</manifest>
Secondly, we use the Application class to determine when the app comes to the foreground and when it does, write the timestamp in Context.CONTEXT_IGNORE_SECURITY mode to share between our apps:
public class MyApp extends Application implements ActivityLifecycleCallbacks {
private boolean appInBg;
private int TIMEOUT = 5000;
private Handler mHandler = new Handler();
#Override
public void onActivityResumed() {
if (appInBg) {
writeToPref();
} else {
mHandler.cancelCallbacksAndMessages(null);
}
}
#Override
public void onActivityPaused() {
mHanlder.postDelayed(new Runnable() {
#Override
public void run() {
appInBg = true;
}
}, TIMEOUT);
}
...
private void writeToPref() {
SharedPreferences prefs = myContext.getSharedPreferences("run_prefs", Context.CONTEXT_IGNORE_SECURITY);
prefs.edit().putInt("last_run", System.currentTimeMillis()).apply();
}
}
Here, we allow a buffer time of 5 seconds to switch between screens. This should be adequate in most cases.
Finally, we can read the written SharedPreference value as follows:
Context context = createPackageContext("example.com.myapp", 0);
SharedPreferences pref = context.getSharedPreferences("run_prefs", Context.CONTEXT_IGNORE_SECURITY);
int lastLaunch = pref.getString("last_run", System.currentTimeMillis());
// Similarly, for other apps.
Hope this solves your issue.

Related

Get the date and time app was opened using SharedPreferences in Android Studio

I am creating an android application using Android Studio.
I need to write a code that saves in a properties file the date and time when the user(for example myself) opened the app.
So anytime the user(me) opens the app, to write that date and time in that properties file.
I guess that this is done using SharedPreferences but I do not find a solution anywhere.
Thank you.
Write this code in your app's Launcher Activity (such as SplashActivity if there):
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String counterKey = "counterKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//doing basic stuff of set layout and all here...
//Initialize sharedpreferences here
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//call to increment counter here
updateAppOpenCounter();
//do remaining stuff here....
}
private void updateAppOpenCounter() {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(counterKey, getAppOpenedCount() + 1);
editor.commit();
}
private int getAppOpenedCount() {
sharedpreferences.getInt(counterKey, 0); //Kept 0 as default opened count if not set to shared yet.
}
You can get the current date by using either new Date() or Calendar.getInstance(), and you could then format this to a String using SimpleDateFormat.
Storing the String representation of the date the app was opened can be done easily using the documentation provided by Google on SharedPreferences.

Android Studio Start Up App Tips And Hints

I've looked around and I'm trying to see if Android Studio has any sort of function for when first term use of the app it shows some messages to help people.
I was thinking of using simple text boxes when on first create off the app/ first launch it would show the tips until they click on each object or item.
I know how to do the click and view just not sure the function to use for when they start the app?
You detect the first launch of your app for instance by loading (and defaulting) a boolean value from your app's preferences.
In your MainActivity
private boolean firstStart = true;
#Override
public void onCreate(Bundle savedInstanceState) {
SharedPreferences prefs = mContext.getSharedPreferences("APP", Context.MODE_PRIVATE);
firstStart = prefs.getBoolean("firstStart", true);
if (firstStart) {
// do your stuff on first start here
// like set "showWizard" or any other flag to true so
// your controls can behave in "firstStart" mode
// Don't forget to save, that it is now no longer the first start...
firstStart = false;
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstStart", false);
editor.apply();
}
}
Maybe try adding them into this:
#Override
public void onCreate() {
super.onCreate();
//put your lines in here
}

How to implement permanent splash screen and 1 time tutorial both in one app [duplicate]

This question already has answers here:
Determine if Android app is being used for the first time
(15 answers)
Closed 6 years ago.
I am new to android development and and I want to setup some of application's attributes based on Application first run after installation. Is there any way to find that the application is running for the first time and then to setup its first run attributes?
The following is an example of using SharedPreferences to achieve a 'first run' check.
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();
}
}
}
When the code runs prefs.getBoolean(...) if there isn't a boolean saved in SharedPreferences with the key "firstrun" then that indicates the app has never been run (because nothing has ever saved a boolean with that key or the user has cleared the app data in order to force a 'first run' scenario). If this isn't the first run then the line prefs.edit().putBoolean("firstrun", false).commit(); will have been executed and therefore prefs.getBoolean("firstrun", true) will actually return false as it overrides the default true provided as the second parameter.
The accepted answer doesn't differentiate between a first run and subsequent upgrades. Just setting a boolean in shared preferences will only tell you if it is the first run after the app is first installed. Later if you want to upgrade your app and make some changes on the first run of that upgrade, you won't be able to use that boolean any more because shared preferences are saved across upgrades.
This method uses shared preferences to save the version code rather than a boolean.
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();
}
You would probably call this method from onCreate in your main activity so that it is checked every time your app starts.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkFirstRun();
}
private void checkFirstRun() {
// ...
}
}
If you needed to, you could adjust the code to do specific things depending on what version the user previously had installed.
Idea came from this answer. These also helpful:
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:
How to get the build/version number of your Android application?
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
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.
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.
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();
}
}
}
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
}
}

Android programming - Want people to enter phone number first time they open my app

I need to know peoples phone number for the app I'm making, because the app revolves around the phone number. Since I can't find any foolproof way of getting the A Number off a phone, I want the very first time someone opens the app, them to enter their phone number. And I can't seem to find something similar to this on google.
Any lads here that got any ideas on how to make this work?
PS.
I'm rather new to Android programming and programming in general!
You can get the phone number with
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
And in Manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
However this wont work all off the time (some comments in similar questions here on SO like this even suggest it hardly works at all).
So what you should do is prompt the user when the app starts, get his input from a textfield or something and store it somewhere you will be able to get it. The best way for you might be to store it in SharedPreferences:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
String phoneNumber = "";
//save
prefs.edit().putString("phoneNumber", phoneNumber).apply();
//read
phoneNumber = prefs.getString(phoneNumber, "");
Similar to this you can save a bool (putBoolean and getBoolean) after you first started the app, so you can keep track of that. Just set it to false after you got the number and check for it every time you start the app again.
Add a new activity and from AndroidManifest.xml make it the launcher activity
public class PhoneActivity extends Activity {
String number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkStatus();
//considering that SliderActivity is your current main activity
if (number.equals("")) { //finish this activity if number already present
Intent sliderIntent = new Intent(PhoneActivity .this,
SliderActivity.class);
startActivity(sliderIntent);
finish();
}
//In xml create an edittext
phoneEditText.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
SharedPreferences.Editor editor = settings.edit();
editor.putString("number", phoneEditText.getText().toString());
Intent sliderIntent = new Intent(PhoneActivity .this,
SliderActivity.class);
startActivity(sliderIntent);
finish();
}
});
}
public void checkStatus()
{
SharedPreferences settings = getSharedPreferences("myPref", 0);
number= settings.getString("number", "");
}
}

I am unable to get Shared Preferences of other application

I am new to Android.I am trying access SharedPreferences of one application in another application.
But i am not getting those values.
My code was posted below.
Create.java in SharedPref1
package com.example.sharedpref1;
public class Create extends Activity implements OnClickListener{
EditText et1,et2;
Button btn;
String LogID,Pwd;
public SharedPreferences loginDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
et1 = (EditText)findViewById(R.id.etC1);
et2 = (EditText)findViewById(R.id.etC2);
btn = (Button)findViewById(R.id.bCreate);
loginDetails = getSharedPreferences("logid", MODE_WORLD_READABLE);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.bCreate)
{
LogID = et1.getText().toString();
Pwd = et2.getText().toString();
Toast.makeText(getApplicationContext(), "User Profile Createad With\nUser ID: "+LogID +"\nPassword: "+Pwd, Toast.LENGTH_LONG).show();
SharedPreferences.Editor store = loginDetails.edit();
store.putString("logid", LogID);
store.putString("pass", Pwd);
store.commit();
finish();
}
}
}
Show.java in SharedPref2
package com.example.sharedpref2;
public class Show extends Activity implements OnClickListener{
EditText log,pwd;
Button back;
public SharedPreferences loginDetails;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
log = (EditText)findViewById(R.id.etid);
pwd = (EditText)findViewById(R.id.etPwd);
back = (Button)findViewById(R.id.bBack);
back.setOnClickListener(this);
loginDetails = getSharedPreferences("logid", MODE_WORLD_READABLE);
log.setText(loginDetails.getString("logid", "defValue"));
pwd.setText(loginDetails.getString("pass", "defValue"));
}
}
I am getting values as below
I am trying access SharedPreferences of one application in another application.
This is a bad idea. Quoting the documentation for MODE_MULTI_PROCESS:
SharedPreference loading flag: when set, the file on disk will be checked for modification even if the shared preferences instance is already loaded in this process. This behavior is sometimes desired in cases where the application has multiple processes, all writing to the same SharedPreferences file. Generally there are better forms of communication between processes, though.
(emphasis added)
Moreover, the only way this could possibly work is if you make the SharedPreferences MODE_WORLD_READABLE, which means any app can get to those preferences. Programmers with talent would not do this, but would use other IPC mechanisms that would limit the communications to between the two applications and only with user permission, so as to not leak user data to others.
Finally, you do not have any code that will work across processes. getSharedPreferences() will get preferences for your own process. The only way I can think of to get a SharedPreferences from another process would require calling getSharedPreferences() on a Context created via createPackageContext(), and I haven't tried this, as I wouldn't dream of implementing what you are proposing.
If you need to share content between applications I would suggest using a content provider and not SharedPrefrences. In my experience SharedPrefernces is unreliable in these situations.
MODE_WORLD_READABLE is depracated in API level 17.
http://developer.android.com/reference/android/content/Context.html#MODE_WORLD_READABLE

Categories

Resources