I developed an android app in which I have added the backup option. Now, I want to add the functionality of prompting the user when they carried the last backup with date and time. And if they didnt do backup then allowing them to do backup.
Please anyone help me with this how to perform this operation?
Assuming you have a backup function:
public void backup(){
//get time of last backup
SharedPreferences sharedPref = context.getSharedPreferences(
"PrefsFile", Context.MODE_PRIVATE);
long time = System.currentTimeMillis();
long lastBackup = sharedPref.getLong("BackupTime", 0);
//if there was no previous backup, lastBackup will be 0
if (lastBackup != 0){
long timeDiff = time - lastBackup; //difference will be in milliseconds
//do what you need with the time difference
}
//code for backup
SharedPreferences.Editor editor = sharedPref.edit();
editor.putLong("BackupTime", time); //update last backup time
editor.apply();
}
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I am planning on implementing a reward system in my android application where users of the application can gain 100 points each day for opening the app. Users can only get 100 points at one given day no matter how many times more then once they open the app. I am not sure how I can go about doing this, for example, a application called WhatsChat, give users credits for opening the app each day:
I am trying to implement a similar system but instead only give users 100 points for opening the app each day. I understand I will need to keep track of the day and maybe store this in local storage using SharedPreferences and keep record of the dates of each day and then increments the variable that records points by 100.
In pseudo code it would look something like this:
Set CreditsGained to 0
IF app launched for the first time on Current date THEN
CreditsGained = CreditsGained + 100
Else
Do nothing
How can I implement a such system in my application?
You do it on the server. The first time they make a network request every day, add 100 points to their total. There's no way to do this securely client side.
I recommend you not use Shared Preferences to save data like you want. Cos they can modify it.
Only 1 way you can secure it, you have to have your own server to keep it. Local storage is not safe too.
But if you want to know how to check that, for studying, you can use Shared Preferences as well.
Step1: get your current time in string:
SimpleDateFormat sdf = new SimpleDateFormat("d-m-Y");
Calendar cal = Calendar.getInstance();
String dateInStr = sdf.format(cal.getTime());
Step2: Check at startup activity.
After onCreate()
SharedPreferences pre=getSharedPreferences("my_sp", MODE_PRIVATE);
SharedPreferences.Editor edit=pre.edit();
if (pre.getBoolean(dateInStr, false)){
//they checked today
}else{
//not today
// use check function here
edit.putBoolean(dateInStr, true);
edit.commit();
}
Okay, put step 1 code above step 2 code, i only separate it for easier understanding.
Step3: After you can check if they have check point more than 1 time or not. Let's add them 100points if that is the first time of the day they check out.
Put this inside else statement, above edit.putBoolean(dateInStr, true);
//get prev_score from SP
long previous_score = pre.getLong("score", 0);
//add 100
previous_score = previous_score + 100;
//save back to SP
edit.putLong("score", previous_score);
I may be late answering to your question..but for others seeking for the reward system and do not want the servers to handle this stuff -->
You can
check whether the Automatic Date and time option is enabled or not in
the user's device
**. Then according to the response, you can give reward to the user.
eg.
calendar= Calendar.getInstance();
year=calendar.get(Calendar.YEAR);
month=calendar.get(Calendar.MONTH);
day=calendar.get(Calendar.DAY_OF_MONTH);
todaystring= year+ "" + month + "" + day + "";
timepref=context.getSharedPreferences("REWARD",0);
currentday=timepref.getBoolean(todaystring,false);
//Daily reward
if (!currentday && isZoneAutomatic(context) && isTimeAutomatic(context)) { //currentday =false
btnrwrd.setEnabled(true);
btnrwrd.setText("Collect your daily reward!");
btnrwrd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Daily reward granted!", Toast.LENGTH_SHORT).show();
// Do your stuff here
// saving the date
SharedPreferences sharedPreferences = context.getSharedPreferences("SAVING", Context.MODE_PRIVATE);
SharedPreferences.Editor edt = sharedPreferences.edit();
edt.putInt("mypoints", Integer.valueOf(points.getText().toString()));
edt.apply();
Toast.makeText(context, String.valueOf(daily), Toast.LENGTH_SHORT).show();
SharedPreferences.Editor timedaily = timepref.edit();
timedaily.putBoolean(todaystring, true);
timedaily.apply();
btnrwrd.setText("Wait for 24 hrs");
btnrwrd.setEnabled(false);
}
});
}
else {
Toast.makeText(context, "Your daily reward is over!", Toast.LENGTH_SHORT).show();
}
public static boolean isTimeAutomatic(Context c) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.Global.getInt(c.getContentResolver(), Settings.Global.AUTO_TIME, 0) == 1;
} else {
return android.provider.Settings.System.getInt(c.getContentResolver(), android.provider.Settings.System.AUTO_TIME, 0) == 1;
}
}
public static boolean isZoneAutomatic(Context c) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.Global.getInt(c.getContentResolver(), Settings.Global.AUTO_TIME_ZONE, 0) == 1;
} else {
return android.provider.Settings.System.getInt(c.getContentResolver(), android.provider.Settings.System.AUTO_TIME, 0) == 1;
}
}
I hope it helps you! Upvote the answer and Good luck :)
Whenever the user opens the app, check if any last credit date is available in the local storage and if it does, verify the current date is one more than the stored date, then you credit the user for next day.
If the date is not available in storage, then you can assume it's the first day. And yes you can do it in MainActivity for this use case because you are not making any time consuming api calls.
I just shared the idea, figure out the code. It's easy.
Hi I want that the application that I have developed to stop working after like 5 days. In short I want to time bomb my android app Can someone tell me how to do this programmatically in android studio? Any possible codes to suit this?
Thanks..
Use the following method to get the timestamp of the moment, when the app was installed for the first time:
private static long getFirstInstallTime(Context context) throws
PackageManager.NameNotFoundException {
PackageManager pm = context.getPackageManager();
PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
return info.firstInstallTime;
}
Now you can calculate the elapsed time and compare it with your desired app lifetime:
long now = System.currentTimeMillis();
if (now - getFirstInstallTime(getApplicationContext()) >
TimeUnit.DAYS.toMillis(5)) {
sendPoisonPill();
}
Note: sendPoisonPill method is your implementation of 'time bomb'
Well,
if you know the time of publications then you can do something (silly) as
class MainActivity extends Activity {
public static final long DESTROY_APP_TH = 432000000;
#Override
protected void onCreate(Bundle savedInstanceState){
PackageManager pm = context.getPackageManager();
PackageInfo pi= pm.getPackageInfo(context.getPackageName(), 0);
long publishTimeInMilli = pi.firstInstallTime;
long now = System.currentTimeMillis();
if(now - publishTimeInMilli) > DESTROY_APP_TH) {
//just finish the the activity (and thus the app) or do something else
finish();
}
}
I am using this code to expire trial version after 26th March.
String currentTime = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
Log.d("timeStamp", currentTime);
Calendar date = new GregorianCalendar(2016, Calendar.MARCH, 26);
date.add(Calendar.DAY_OF_WEEK, 0);
String expireTime = new SimpleDateFormat("yyyyMMdd").format(date.getTime());
int intcurrentTime = Integer.parseInt(currentTime);
int intexpireTime = Integer.parseInt(expireTime);
if(intcurrentTime == intexpireTime || intcurrentTime > intcurrentTime ) {
//logic to set off the features of app
tvJ2.setText("Trial period expired!!");
}
You can use AlarmManager to send an intent to your app at the specified time. Have that intent handler close your app.
Please bear in mind, however, that depending on what exactly you want to do, this is, likely, not a good thing. An Android app running (i.e. - has a process that gets scheduled by the kernel), open (i.e. - has a view that the user can change to) or active (i.e. - it is the foreground view) are almost independent states. You need to specify which is what you want to expire.
You could create app with subscription, such that after 5 days subscription expires and app becomes useless (can't be started)
In my implementation, I will add 1 variable to SharedPreference.
for example firstRun timestamp. Each time the app launch, I will get that variable and check it with the current time of the app. It is longer than 5 days (your setting), so terminate the app. But this way can't help if users change system time in their device.
The safer way is you should send this variable firstRun to your server. And each launching time, the app will request server and check condition inside your server.
Hope it helps!
I don't understand why do you want to do that, but anyway, you could create a String with a date and save it to SharedPreferences. In your main activity, before doing anything you compare the actual date with the date that you have saved in SharedPreferences (the saved date could be the first time that the application was opened or a prefixed date) and if the actual date is 5 days or more after your saved date, you can display a blank activity or whatever you want.
I have erite for you a code, where the first time you open the app the system saves the date and adds 5 days more. Then every time you open again the app you compare the saved date with the actual date, and if the actual date is after your saved date (it means that it has passed 5 days) you do whatever you want
class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
if (!prefs.getBoolean("firstRun", true) {
SharedPreferences.Editor editor = prefs.edit();
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, 5); // number of days to add
String date = sdf.format(c.getTime()); // dt is now the new date
editor.putBoolean("firstRun", true);
editor.putString("valid_until", date).apply();
}
else if(new Date().after(sdf.parse(prefs.getString("valid_until","")))) {
//Show whatever you want. Or finish the activity calling to finish();
}
}
I want to implement voice actions, "start running" and "stop running".
"Start running" works fine, but "stop running" doesn't work.
My app has one activity with several fragments.
When I speak "stop running", the activity is destroyed and created. My workout data is lost.
setRetainInstance(true) has no effect.
Change launchMode to singleTask/singleTop/singleInstance has no effect.
I saved workout data in onSaveInstanceState(), but it's lost when a new activity is created.
Is there any other way?
I'm not sure if this is too obvious, but have you considered using SharedPreferences?
To save data:
sPref = getPreferences(MODE_PRIVATE);
testNum = 2;
SharedPreferences.Editor editor = sPref.edit();
editor.putInt("testName", testNum);
editor.commit();
To get data:
sPref = getPreferences(MODE_PRIVATE);
int retrievedTestNum = sPref.getInt("testName",-1);
System.out.println("The number you saved was " + retrievedTestNum + "!");
You can also save data in arrays and store it in the SharePreferences.
If this is too simple for you, you can grab a mySQL database, which is much more robust.
This might seem a little weird!!
But I was wondering if I could add some help on my app .which comes when You first open your app and when you touch the screen it vanishes(Only comes in first run).
The problem is I didn't even know what is this thing called I tried a search on google but I'm nowhere near it.
It will be very helpful if anyone can provide some info about that(what is it called ,How to add it in your App)
Thanks !!
Check my answer for some thing on first setup.
Put this on first time run.
shPref = getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
SharedPreferences.Editor pref_editor = shPref.edit();
pref_editor.putBoolean("first_time", false);
pref_editor.commit();
Check it like this:
shPref = getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE);
boolean isFirstRun = myPrefs.getBoolean("first_run",false);
if(isFirstRun){
txtViewHelp.setVisibility(View.VISIBLE);
//logic of making it invisible on touch outside
}
else
txtViewHelp.setVisibility(View.GONE);
Hope this helps.
Try this!
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean previouslyStarted = prefs.getBoolean(getString(R.string.pref_previously_started), false);
if(!previouslyStarted){
SharedPreferences.Editor edit = prefs.edit();
edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE);
edit.commit();
**// when the application is previously opened
//Show your help Test**
}
else
{
**// when the application is opened very First Time**
Intent intent = new Intent(MainActivity.this, Home_Module.class);
MainActivity.this.startActivity(intent);
}
This will Help You.
It stores your application status that it is previously opened or not?
I am developing an android app and I want it to do a particular action(say for example, go to a particular URL) when the user loads it for 'N' times. How do I go about doing it. I know its got to do with SharedPrefs and Activity LifeCycle but I am not being able to get a headstart into it. Can someone plz suggest how to proceed.
Use the onCreate method in your activity to set a counter in SharedPrefs. Increase it by 1 each time and when it reaches N, do your thing..
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
int count = sharedPreferences.getInt("count", 0);
if (count == N) {
...
} else {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("count", count + 1);
editor.commit();
}