How disable destroy my activity - java

My app contains Activity. I start it by Intent. Than I turn my Activity to background (switch to Home Screen or similar). After some time the OS destroy my Activity (I think when memory is low). It is possible protect my Activity (in background) from destroy by OS? Or increase it priority to maximum?

Activity is made for a UI holding elements. Service is made for background tasks. From this already sounds logic to make a Service instead of try to keep Activity in background.
Also there are BroadcastReceivers, which will be called on different actions. Boot completed, Internet lost, got and so on.
I think you know what do you want to archive, I would suggest telling in detail an will get a lot better response, with enumeration, maybe code part of component needed to use.
Keeping Activity forced alive is a bad idea in general.

You can load WebView in background.

Related

Perform an Action when the app comes to foreground

I am developing an app which has to perform some background work. For that reason, I am using a Service. Now what I want to achieve suppose the user start the background work and while the work is loading then the user has an option to either minizine the app or wait till the loading is over.
After the loading is over I want to open another Activity. Now my issue supposes the user starts the loading and minimizes the app then when the loading is over the user has not yet returned to the app then if I start the Screen without even the user having my app in his view then the user might get interrupted with his work.
So what I want is when the loading is over, I want to only open if my app is visible to the user and if the app is not visible to the user then I want to wait till the user return back and only when the user returns back I want to open the Screen if the loading is over.
Now what I have thought is I should have a boolean which will track whether the app is visible to the user. On onStop I will set the boolean value to false and onStart I will set the value to true. And again onStart I will check if the loading is finished and if yes then I will open the Screen.
But I want to know whether there is a better way to achieve this? If yes then how. The reason I am looking for a better way is that I want to write a clean code for my app which might avoid bugs and crashes.
That is exactly the scenario LiveData and RxJava are for. Your activity will get the data only when the activity is visible. Your Viwemodel will provide your live data to the activity only when your activity is available and it's lifecycle aware. You can also consider using WorkManager if your app needs to continue to work even after your user closed your app, even if user restarts your app. It also comes with Constraints to optimize your work based on Network, Battery life...and provides livedata for your Viewmodel to consume.

What are the Advantages and disadvantages of AsyncTask in Android framework?

I am learning Android app development from Udacity.com by Google engineers and they said,
"It is not a good idea to use 'AsyncTask' as it is not attached to an activity life cycle. The virtual machine will hold on to the activity object as long as the Asynctask is running, even after Android has called onDestroy( ) method for the activity and expect it to be discarded.
If you rotate your phone, the behavior is to destroy the current activity and instantiate a new one. The naive AsyncTask implementation now has two threads trying to do the same update. So it is not the best pattern for a potentially very long running background operation , such as fetching from web services. If you leave the app, the asyncTask will run as long as as the process is kept alive , but will run at a lower priority, and your process will be the first thing to be killed if the device needs more resources. "
1) If using AsyncTask is disadvantageous why was it created? What would have been the design philosophy or the cause to create it in spite of having services(or something similar to achieve same kind of functionality)?
2) What are the situations where Asynctask should be used for betterment compared to Services/similar options available in Android?
3) What are the situations/places Asynctask should never be used?
Please do not downvote this question. I searched Stackoverflow and I couldn't find a similar question.
Advantages of AsyncTask
Provides generic solution for all network calls
Publish progress to UI while executing.
Run Asynchronously
Easy to maintain and read.
Problems in AysncTask
When you rotate your screen, Activity gets destroyed, so AsyncTask will not have a valid reference to publish data from onPostExecute(). In order to retain it, you need to usesetRetainState(true) if calling from fragment or onConfigChanges() if calling from activity method of an activity.
If activity gets finished, AsyncTask execution will not cancelled automatically, you need to cancel them else they will keep on running in the background.
If any exception occurs while performing network task, you need to handle them manually.
Whereas AsycTask, Services, IntentService, Threads all run on different threads and all serve different purpose.
please read more detail here.
So you need to decide when to use which component while performing non UI operations.

invoke a method from activity in another

i know that this question was asked before but i had tried all the solution and get Error
i have two activity on android studio ...
the first called 'MainActivity' and contain a method ' deleteFromArrayList() '
the secound on called 'DeletButtonActivity' and contain a method ' delete(View v) '
i want to invoke 'deleteFromArrayList ()' wihtout creating another class or make the method static .... becouse i have an ArrayList inside deleteFromArrayList()
note : i send value of index i want to delete from array list using Intent ..the code in DeleteButtonActivity is
public void delete(View v) {
try {
Intent i = new Intent(DeleteButton.this, MainActivity.class);
i.putExtra("index", (int) spinner2.getSelectedItemId());
(new MainActivity()).DeletButtonActivity();
Toast.makeText(getApplicationContext(), "it was deleted", Toast.LENGTH_SHORT).show();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e+"", Toast.LENGTH_SHORT).show();
}
}
and the code in MainActivity
public void deleteFromArrayList (){
this.arrayList.remove(getIntent().getIntExtra("index",-1));
}
when i run the app i got an Error NullPointerException,,,
can anyone help me ..please
hope that i describe the problem very well
Activities in Android are no just a simple class but they also have a Lifecycle:
An activity has essentially four states:
If an activity is in the foreground of the screen (at the top of the
stack), it is active or running. If an activity has lost focus but is
still visible (that is, a new non-full-sized or transparent activity
has focus on top of your activity), it is paused.
A paused activity is
completely alive (it maintains all state and member information and
remains attached to the window manager), but can be killed by the
system in extreme low memory situations.
If an activity is completely
obscured by another activity, it is stopped. It still retains all
state and member information, however, it is no longer visible to the
user so its window is hidden and it will often be killed by the system
when memory is needed elsewhere.
If an activity is paused or stopped,
the system can drop the activity from memory by either asking it to
finish, or simply killing its process. When it is displayed again to
the user, it must be completely restarted and restored to its previous
state.
So the problem with your code is that when you want to access the array in a stopped activity, the instance you have been using before might not be alive anymore.
How to solve your problem
A very simple approach is to use parameter passing before you do the transition from one activity to the other, for this you'd pass your Array as an intent extra and then you "get the result back" when you finish the second activity by using onActivityResult() callback.
A second approach could be to use a Service that is something similar to an Activity but it has no UI and it has its own lifecycle. Being able to be alive even when you app it is not. Using a Service, you'll keep the Array inside the service and you'll communicate with the array to do the usual operations.
A third approach could be to use an EventBus. A very simple communication mechanism between Activities, Fragments, Threads, Services. There's a great talk titled Android Application Architecture on Android Dev Summit 2015 that uses EventBus as a communication mechanism and to implement a MVC architecture pattern on a REST Android App.
Back to your question. If you just need to 'share' an array between two activities, use the first approach. The second and third are just examples of different alternatives for the case you need a lot more than that.
You must not do this. There are mechanism to communicate between activities or fragments.
On can be, using startActivityForResult, this is Activity A calls Activity B, then in B you do something, and communicate the result back to Activity A.
You can have another workaround to what you want. If you can access the data in both of your activities, you can modified in ether one of them, when the activity starts, it will show the updated data.
Please first read well about an Activity here, and also provides more context of your question.

Android task lifecycle and static data, is a task ever destroyed?

Android activities have a well defined lifecycle and they will be paused, stopped, and destroyed. That is very well documented. My question is about the task that contains my activities as described in the docs.
Under low memory or other conditions, will the task ever be shut down by the OS? (I understand the user can Force Stop the app).
Can I assume my Singletons and static data will always be available?
What about static members defined on an Activity? It appears that the Activity may be destroyed, but the static data lives as long as the task lives.
android.app.Application has callbacks like onLowMemory() and onTrimMemory() but these seem to be voluntary, meaning it is great if the app cooperates with the OS, but it doesn't have to. So, I'm pretty certain my task is never normally killed and singletons and statics are reliable. Is this correct?
This answer also had some good background.
I was extremely curious about your question and so I quickly did a simple check with a very simple project and I'll post what I found - I'll answer the rest based on hypotheses as Android's clean up process is quite arcane.
Created 3 activities - A, B, C. A can call B or C. A is the starting
point of the app. B and C cannot call anything. C has a static
integer member x.
x is a class member of C and initially does not have any value. I set
it to 5 and printed it out in the onCreate() of C. It is also printed
out in the onResume() of A.
When I started the app, a toast was displayed on A which said 0 (C.x
has not been set yet). Then I navigate to C. I get a toast c=5.
Then I press back and go back to A. I get a toast c=5. C has been
destroyed.
Then I go to B. No toast. Go back to A. I get a toast c=5.
From A, I press home. From home, I again reopen the activity. I get
c=5.
I press back to go back to home (destroying A). Then I reopen the
app. I get c=5.
Then I go back and force stop the app from settings. Then I reopen
the app - I get c=0. Force stop completely removes everything from this task.
From this, you can say that static values continue to exist even after the Activity has been destroyed. Even after an application is closed, the value is still retained by Android.
Can I assume my Singletons and static data will always be available?
I would say that you can assume this as long as Android is not pushed to the point where it decides that memory needs to be reclaimed.
From the Android tutorial book by Commonware, I understand that any task that is running in the background is considered as an important task and will not be shut down by Android. But if another task comes to the foreground, then this is given a higher priority and all tasks in the background assume lower priority. If Android decides the task in the foreground needs more memory, it will start killing processes based on order of priority which depends upon a number of factors. Under low memory conditions, any task can be killed. In extreme cases, the task on the foreground itself may be killed.
I hope this answers your question. It certainly piqued my interest.
Can I assume my Singletons and static data will always be available?
You can never assume that. Sometimes contex changes (when you go to the settings and turn gps on for instance) and then your apps is being recreated. OS can destroy your activity in any time. You should never operate on static data even on PC programs
It seems that the OS can kill your task in low memory and other situations. And, of course, your statics and singletons die with the task.
If you need your statics and singletons to survive task shutdown and restart, you need to persist them somewhere. Android Application Framework FAQ has good suggestions. I found that you can leverage onSaveInstanceState() and save your data as part of the save instance bundle. It will be restored when the Activity is restored. See Controlling Android Activity restart after a process stops

ANR problem in my app

I have quite a heavy Activity with a lot of things going on in the UI Thread, and also other Runnable threads within the Activity. Within this main activity I start a new Activity with a button press which is called using startActivityForResult(). Now when I start the new activity I get an ANR error meaning that there is something taking longer than the set amount of time and I get the ForceClose/Wait Dialog pop up.
The thing is, for the new Activity I am only setting the contentView for the activity and nothing else so it means something from the previous Activity is causing it to hang. It has never down this before in the app only recently and I can't think what I have added for it to cause this.
In the first Activity I have OpenFeint, SurfaceHolder.Callback, database calls in background thread and lot's of image manipulation. Are any of these processes hungry enough to cause the ANR?
Could I possibly put the first activity on hold while the second one loads (I thought it did that anyway)? Like I say the second Activity does nothing other than load a ContentView.
When you start a new activity, the previous activity should be put on hold, as you say. But first the activity's onPause is called. Maybe it's this method which causes the ANR? Especially if it is saving large amounts of state data.
Just guessing here.
The fact that there is an ANR it is pretty clear that something is running longer in the UI thread (as you have pointed out). Also, you seem to be doing a lot of things (at least the explanation gives this feeling). At this point I can say try commenting out certain parts and see if the problem persists. E.g. comment the startActivityForResult(), this should tell you which activity is the culprit. Also, if you can put up some pseudo code, I'm sure people would get a better idea and would be able to help better.
The ANR occurs usually when you solicit the UI (like pressing a button), so I think it's not the second activity launch which causes the ANR, but the fact you use the UI.
So the problem is from your first activity, not the second.

Categories

Resources