Removing Preference data when Application killed - android

In my application i am storing some SharedPreference data.
I have to clear that all stored data when application killed.
So, I have done it in my activity's onDestroy() as below :
#Override
protected void onDestroy() {
if(isBackPressed==0){
if(Prefrences.checkPref(MyActivity.this,MAIN_PREF)){
Prefrences.removePref(MyActivity.this,MAIN_PREF);
Prefrences.removePref(MyActivity.this,PREF_1);
Prefrences.removePref(MyActivity.this,PREF_2);
Constant.displayLogE(">>>>>>>>>>","### Prefrence removed ");
}
Constant.displayLogE(">>>>>>>>>>","### Destroy activity ");
}
finish();
super.onDestroy();
}
Here, I have taken isBackPressed because, When onBackPressed called it calles finish() automatically and onDestroy() method calls. So, I have initialized isBackPressed to 1 inside onBackPressed() method.
It doesn't matter, I just have to remove my prefrence data when app going to be killed. But, the issue is when I killing app, onDestroy() methos not calling.
Thanks.

try this way.
public class App extends Application{
#Override
public void onCreate() {
doSomeCleanWork();
}
}

Related

Is it possible to clear data from shared preference when app is cleared from recent list.?

I have to clear the data from SharedPreference when the app is cleared from recent list.
Is there any way for that ?
Which activity is called when app removed from recent list in android?
The above link tells you how to enter a callback method on removing app from recent list. You can then update your shared variable in that function.
I don't think so,when the app is cleared from the background the onDestroy() method does not get called most of the times. Hence the app does not get any callback method to do so.
If you want to do that then why don't you use some static variable or objects (if that is possible) in application class,depending on the requirement. They will get reinitialized each time the application launches, may be if that can help you.
As already said, there is no guarantee that you will receive a callback when you app is killed no matter what callback you try to use. However, I'm still wondering why you are using the SharedPreferences if you do not want that data to be persistent, it's beside the point of this class. That being said, you should handle the data like any other data inside your app.
If you are required to use the SharedPreferences for some reason, then the proper way to clear it is when you start the application, not when you kill it. This way, you won't have any problems.
You could do that using a Service.
Create a Sticky Service:
and override the onTaskRemoved function to clear your Shared Preferences.
public class CheckAppRemovedService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
//YOUR CODE TO CLEAR SHARED PREFS.
}
}
Start the service when you start your activity.
Intent intent = new Intent(MyActivity.this, CheckAppRemovedService.class);
startService(intent);
When an app is cleared from the recent list, the onDestroy() method will be called. So clear your SharedPreference values when the onDestroy() method will be called.
#Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences.Editor editor = getSharedPreferences("APP", MODE_PRIVATE).edit();
editor.putString("YOUR_DATA_KEY", "").apply(); //data nullified
}
See the lifecycle of an activity in android below:

How to check activity has been destroyed or no more running

I am working on an android app and have an activity. I have written a code in my activity that will start a new activity after getting response from server, this code is getting executed even after I press back button on my activity.
So, I want to check that if my current activity is not active anymore, then the code should not run.
How can I check that activity is not running or in existence any more.
Please help me if anyone know how to do this.
Thanks a lot in advanced.
Activity is still in memory that's why your code is executed to finish it completed call finish() after starting another activity.
To check if current activity is there or not you have to override onDestroy() method which is called everytime when your activity is completely destroyed.
For checking activity is running or not follow this question
just call finish() method when you starts a new Activity
like
Intent intent = new Intent(this, NextActivity.class);
startActivity(intent);
finish();//this activity has been finish and the code will not execute
you can check if Activity is destroyed or not.
override this method
public void onDestroy() {
super.onDestroy();
Log.d("Activity name,"destroyed");
}
Try like this
class MyActivity extends Activity {
static boolean isActive = false;
#Override
public void onStart() {
super.onStart();
isActive = true;
}
#Override
public void onStop() {
super.onStop();
isActive = false;
}
}
Check here : Proper way to know whether an Activity has been destroyed
The question have your answer and as the solution provided just use the SharedPrefrence to store the variable.

Android - How to know when app has been resumed after being in background

I'm trying to determine when my app is being resumed after the user closed it, in any way, pressing home button, back button or switching to another app.
What I need to do is to set a boolean when the app goes in background, so, when it is resumed, I know that it was in background before and I can act accordingly.
I tried to use onResume and onPause methods in activities to know when the app goes in background and it is then resumed, but as only one activity can be alive at at time, I had no success. When an activity is paused, this doesn't mean that the app went to background, because another activity could have been launched, but the onResume event of that activity will trigger only after the previous one has paused.
I've also tried to list all the apps in foreground, but with no success, if I put my app in background resuming another app, my app always results to be in the foreground.
I read that since Android 4 there is a new method to know when the app is in foreground, but I need my app to be compatible with Android 3.0 devices too.
Here is the code I tried putting in every single activity (MyApp is my Application name):
#Override
protected void onResume() {
super.onResume();
MyApp.isPaused = false;
}
#Override
protected void onPause() {
super.onPause();
MyApp.isPaused = true;
}
This is also my attempt to list all the apps in foreground:
ActivityManager activityManager = (ActivityManager)((Activity) currentContext).getSystemService( ACTIVITY_SERVICE );
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for(RunningAppProcessInfo appProcess : appProcesses){
if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
if(appProcess.processName.equals("com.xxx.myapp")) {
Log.i("MyApp", "it's in foreground");
}
Log.i("MyApp", appProcess.processName);
}
}
This class provides a singleton to determine "the activity in background" status. It uses a timer with a threshold(i.e. 0.3s) to determine the activity is went to background or not.
One thing has to point out is that if the user resumes to the activity within the threshold (i.e. 0.3s), this test will be failed.
If you have a better solution, please share with us :)
Ref: https://gist.github.com/steveliles/11116937
You are absolutely correct :) Because only one activity can be alive at a time so you need something which remains alive through out the application life cycle :) like Application instance itself or you can also make use of shared preference for that matter. But seriously using shared prefference for checking lifecycle is wrong choice if you ask me.
If I was in your position I would have gone for Application class :) Here is code if you want to do the same :)
import android.app.Application;
/**
* Created by sandeepbhandari on 3/3/16.
*/
public class AppService extends Application{
private static AppService sInstance;
public static boolean isGoingToBackGround=false;
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static AppService getInstance() {
return sInstance;
}
}
In all your activities onPause just set
AppService service = AppService.getInstance();
service.isGoingToBackGround =true;
And in onResume check the same variablethats all :) and yeah if you want to use your application class rather than default Application you have to make change to manifest.xml
<application
android:name=".AppService"
Thats all :)
Override onTrimMemory(int level) in your Application. Might not be the prettiest way, but it has worked for me.
You will get
TRIM_MEMORY_BACKGROUND = 40;
when your application went into the Background.
You can make Application class inside your project to save state of your project. When any activity goes to pause call on pause respectively while on resume call on resume method and save state of the inside this class. Even if one activity goes on pause another on resume your class will know exact state of the application. Or another way you can save applicaton state in shared preference in each activity can change its value.
i trust there is no need for u to post a code... that being said...
start by logging every implemented methods onCreate(), onPause(), onDestroy(), and other well reputed Activity methods...
but back button does not just pause it kills, thus onCreate is called most
and check onStart() too.
public class CustomApplication extends Application {
private static boolean activityVisible;
#Override
public void onCreate() {
super.onCreate();
}
public static boolean isActivityVisible() {
return activityVisible;
}
public static void activityResumed() {
activityVisible = true;
}
public static void activityPaused() {
activityVisible = false;
}
}
and in your all activities set
#Override
protected void onResume() {
super.onResume();
CustomApplication.activityResumed();
}
#Override
protected void onPause() {
super.onPause();
CustomApplication.activityPaused();
}
and in your manifest
<application
android:name=".CustomApplication"

Can we destroy activity without call stop() method?

In activity life cycle to execute as like.
onCreate()
onDestroy()
it means without call stop() method in activity life cycle.
how it is possible ?
Use finish(); to destroy activity.
You don't need to call stop() method. Android system automatically go thru those life cycle methods.
But apparently onDestroy() always called after onStop().
If you want to kill activity just call finish(), it will destroy your activity.
But remember again onStop() always called as system level, follows the activity life cycle if you call finish().
Note: If system kills your application or activity to utilize memory there is no guarantee to call these methods from activity life cycle.
public class ExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.empty);
System.out.println("in onCreate");
finish();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
System.out.println("in onDestroy");
}
}
when the activity run then call onCreate() method and onDestroy()
method

Can i put flurry code in onCreate() and onDestroy()?

I am trying to use flurry for my android app. It says that i should put flurry code in onStart() and onStop() methods. I dont have these methods in my code. I have two activities and both use onCreate() and onDestroy() methods only. Can i put flurry code in that? Will there be any problem with it?
onStart() and onStop() are methods that handle part of an activity lifecycle, so you can add them to your activities without any problem.
#Override
protected void onCreate(...) {
super.onCreate(...);
...
}
#Override
protected void onStart() {
super.onStart();
FlurryAgent.onStartSession(this, "your_key");
}
#Override
public void onStop()
{
super.onStop();
FlurryAgent.onEndSession(this);
}
onStart and onStop are existing methods on an Activity, just like onCreate. If you want to add functionality at these points of the activity lifecycle, you can override them just like you did for onCreate.
public class MyActivity extends Activity {
#Override
protected void onStart() {
super.onStart();
FlurryAgent.onStartSession(this, "FLURRYKEY");
}
#Override
public void onStop()
{
FlurryAgent.onEndSession(this);
super.onStop();
}
}
onCreate and onDestroy are not an appropriate pair of methods to use for Flurry session tracking because onDestroy is not guaranteed to be called. See the documention on onDestroy. You can end up with situations where the app gets killed by the system and Flurry will think the session is still going.
There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

Categories

Resources