How can I call function 1 time only with Android service? - android

Please read carefully because it is a little bit complicated!
I have a service that call many functions every 5 second. Now I want to call one specific fucntion in those functions just 1 time only. So I make this to check if that function has called before.
private void checkFirstLaunchApp() {
final String HAS_RUN_BEFORE = "hasRunBefore";
final String HAS_RUN = "hasRun";
SharedPreferences runCheck = getSharedPreferences(HAS_RUN_BEFORE, 0);
Boolean hasRun = runCheck.getBoolean(HAS_RUN, false);
if (!hasRun) {
SharedPreferences settings = getSharedPreferences(HAS_RUN_BEFORE, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean(HAS_RUN, true); //set to has run
edit.apply(); //apply
//do that function
functionIWant();
}
} else {
//do nothing
}
}
But the problem is if I close my app and reopen it,that function will not be called anymore. What I want is when I reopen my app, that function will be called 1 time again.Please show me how can I do that?

you have to reset HAS_RUN to false inside onStart() of your launcher activity.
Alternate
Extend Application class and create global variable:
public class MyApplication extends Application{
public boolean hasRun;
public void onCreate (){
hasRun=false;
}
}
Get instance of MyApplication
MyApplication app=(MyApplication)getApplication();
if(!app.hasRun){
app.hasRun=true;
// do your stuff
}

Handle it in the onResume method

Use global variable instead of SharedPreferences

A field variable is fine, sharedpreferences is not suitable for this case.
private boolean mIsCalled;
...
private void functionIWant() {
if (mIsCalled) return;
mIsCalled = ture;
// your function body
}

Set SharedPreference to false in onStop() method :
SharedPreferences settings = getSharedPreferences(HAS_RUN_BEFORE, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean(HAS_RUN, true); //set to has run
edit.apply(); //apply
Call your method in onResume() method :
checkFirstLaunchApp()

Related

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
}

Shared Preferences not getting right Default Value

I made one class with name session and i maintain my all shared preferences from there only like..
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
Now from UI application i call this session and my all variable didnt get there default value like..
public void setIsFirsTimeCall(boolean IsFirsTimeCall) {
prefs.edit().putBoolean("IsFirsTimeCall", IsFirsTimeCall).commit();
prefsCommit();
}
public boolean getIsFirsTimeCall() {
return prefs.getBoolean("IsFirsTimeCall", true);
}
so when i call for getIsFirsTimeCall() then it will give false to me
I don't know why it is doing this
But when i copy and share this project to other PC then its work fine
Have you ever seem this type of behavior
I don't know if this can help you to solve:
I think you can do something like this:
public static void setIsFirsTimeCall(Context cntx, boolean IsFirsTimeCall) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
prefs.edit().putBoolean("IsFirsTimeCall", IsFirsTimeCall).commit();
prefsCommit();
}
public static boolean getIsFirsTimeCall(Context cntx) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
return prefs.getBoolean("IsFirsTimeCall", true);
}
I've moved the declaration and definition of prefs from the constructor of Session class, inside each method that require it. Each of this methods is static, so you can call them from outside the Session class in this way: Session.getIsFirsTimeCall(yourContext) and so on.
Maybe you have to change the behavior of your code because I don't know if your method prefsCommit() can become static, otherwise you can't call it from a static method.
Hope it will help you

Run code on first OnCreate only

I have a piece of code that I only want to run the very first time a particular OnCreate() method is called (per app session), as opposed to every time the activity is created. Is there a way to do this in Android?
protected void onCreate(Bundle savedInstanceState) has all you need.
If savedInstanceState == null then it is the first time.
Hence you do not need to introduce extra -static- variables.
use static variable.
static boolean checkFirstTime;
use static variable inside your activity as shown below
private static boolean DpisrunOnce=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run_once);
if (DpisrunOnce){
Toast.makeText(getApplicationContext(), "already runned", Toast.LENGTH_LONG).show();
//is already run not run again
}else{
//not run do yor work here
Toast.makeText(getApplicationContext(), "not runned", Toast.LENGTH_LONG).show();
DpisrunOnce =true;
}
}
use sharedpreference...set value to true in preference at first time...at each run check if value set to true...and based on codition execute code
For Ex.
SharedPreferences preferences = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
if (!preferences.getBoolean("isFirstTime", false)) {
//your code goes here
final SharedPreferences pref = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
}

SharedPreferences.getBoolean returns true everytime

I made a class for handling important data changes such as App Purchase Status and other stuff .
For this goal I have created a class which does the setting and reading of the values. but the problem is whenever I call the appIsPurchased() method, the result is true while it hasen't been changed since app installation and its first initial launch.
This is my code:
/**
* Created by neemasa on 5/29/14.
* This class handles more crucial data values within app.
*/
public class AppCore {
private SharedPreferences settings;
private String keyPurchase = "app_purchased";
private Context context;
public AppCore(Context context){
this.context = context;
settings = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setAppInPurchasedMode(String status){
if (status.equals("successful")){
settings.edit().putBoolean(keyPurchase, true).commit();
}else if (status.equals("failed")){
settings.edit().putBoolean(keyPurchase, false).commit();
}
}
public boolean appIsPurchased(){
boolean purchased = false;
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
return purchased;
}
}
Question 1st: is there something wrong with my code? if there is then why appIsPurchased() always return true?
Question 2nd: do all values in the shared preferences are true by default?
Meanwhile when I use this class in my code the toast "Purchased!" runs even when app is running for the first time.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCore appCore = new AppCore(getApplicationContext());
if (appCore.appIsPurchased()){
Toast.makeText(getApplicationContext(),"Purchased!",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"Not Purchased!",Toast.LENGTH_SHORT).show();
}
}
Actually there is a problem in your code!! thats why its always showing purchased!!
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
in this lines if the keyPurchased tag if not used , u are passing true value by default
so when u call
if (appCore.appIsPurchased()){
it always return a true value.. The solution is that make sure that the preference values are set before u call them.. hope this helps
Found It, the problem is that I was thinking
settings.getBoolean(keyPurchase,false)
returns the value of keyPurchased variable but the fact is it only returns the variable itself not its value so I fixed the problem by changing the method of my class to this:
public boolean appIsPurchased(){
return settings.getBoolean(keyPurchase,false);
}
you are setting the default value to true, so either your sharedpreference does not contains an entry for key_purchased or setAppInPurchasedMode is never called or is called wit status successful. On the minor side, your
public boolean appIsPurchased(){
boolean purchased = false;
if (settings.getBoolean(keyPurchase,true)){
purchased = true;
}
return purchased;
}
can be implemented like:
public boolean appIsPurchased(){
return settings.getBoolean(keyPurchase, false);
}
about setAppInPurchasedMode, if I were in you I would change the way you compare status, this way:
public void setAppInPurchasedMode(String status){
if ("successful".equals(status)){
settings.edit().putBoolean(keyPurchase, true).commit();
} else if ("failed".equals(status)){
settings.edit().putBoolean(keyPurchase, false).commit();
}
}
the difference is that if status is null, the way you implemented will crash your application with NPE. With my implementation you'll get false, because "successful" instanceof null is always false, and instanceof is the first check for equals
For those still having a problem, remember to apply the changes to your preferences.
private SharedPreferences sharedPreferences ;
private SharedPreferences.Editor sharedPreferencesEditor;
sharedPreferencesEditor.putBoolean("myVariable", false);
sharedPreferencesEditor.apply();

Android initialization with SharedPreferences

I have a problem with SharedPrefences and initializations.
My application has a login where you insert an user, and for that user, you have a specific preferences... so, I need to save preferences according to the user to load it later.
I though that SharedPrefences would be the solution, and it really is I think, but I have a problem to initialize they: I have an Activity class called Options. It has static functions that returns the value of the options... but I have a problem, I call that functions before I have create that activity (intent), so I think that the functions are returning the last value that the last user has selected on the options...
How can I load the options before that calls?
I though to use first of all an Intent sending extra data with the user and in onCreate() of the Options, initialize they, but if I make an intent, then the Options will appear (xml will load).
Any help pls?
Try something like this.... adding methods for each variable you want to save.
public class PreferenceManager {
private static PreferenceManager self;
private SharedPreferences preferences = null;
private SharedPreferences.Editor editor = null;
private boolean isInitialised = false;
private static final String MY_PREFERENCE = "mypreferencekey";
private String myPreference = null;
public void initialise(Context context) {
if (!isInitialised) {
preferences = context.getSharedPreferences("MyPreferencePlace", Context.MODE_PRIVATE);
editor = preferences.edit();
loadPreferences();
isInitialised = true;
}
}
public static PreferenceManager getInstance() {
if (self == null) {
self = new PreferenceManager();
}
return self;
}
private PreferenceManager() {
}
public void setPreference(String newPreferenceValue) {
this.myPreference = newPreferenceValue;
savePreferences();
}
public String getPreference(){
return myPreference;
}
private void savePreferences() {
editor.putString(MY_PREFERENCE, myPreference);
editor.commit();
}
private void loadPreferences() {
myPreference = preferences.getString(MY_PREFERENCE, null);
}
}
All the SharedPreferences need is a context and it can be initialized. As your application always opens an Activity to start with, you always have a context to work with.
I would advise you to wrap the SharedPreferences in a Singleton class and just pass a context as parameter at the getInstance method. You should be able to access your shared preferences at all Activities this way.
I work on the dependency injector for android, and content of shared preferences is already injectable into annotated fields ( see: https://github.com/ko5tik/andject , PreferenceInjector). Patches and improvements are welcome. Saving of preferences comes soon

Categories

Resources