Android Application not releasing memory and not closed - java

I coded program when i press "back", finish application and stop all service.
But after finish, Android studio says application is not closed, and profiler still say app is not closed and using memory.
How can I release all memory and close application without System.exit(0) and android.os.Process.killProcess(android.os.Process.myPid())?
Here's code when I used at test.
#Override
public void onBackPressed(){
finishAndRemoveTask();
}
#Override
protected void onDestroy(){
// Stopping notification listener service
stopService(serv);
// Removing notification
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICES)).cancel(0);
System.out.println("Goodbye, Cruel world.");
}

Related

How To Run A Code or Full App on Background

my App get a Notification when i get time Like Alarm i Just want to Run my app on Background to Can Push my Notification when time come
i was Try to Search about that Problem and ask on Many Android Groups and i Use then a Thread but Nothing work
if (level==100){
Thread T1 = new Thread(new Runnable() {
#Override
public void run() {
// PushNotification Method
PushNotification();
}
});
T1.start();
}
The Code only Run when App Open but When Close the App the Code Not work
If you're trying to receive notifications from GCM, then create a WakefulBroadcastReceiver that can be used to receive the notification and handle it appropriately.
On the other hand, if you're trying to send a normal notification from within your app, then create your own background Service that can be used to send the notification. Here's a link to a similar SO answer that you can use for reference.

Activity of my app goes into background sometimes after I turn off the screen

I am running Camera as a service attached to an activity. There are other services such as upload and Firebase are running along with the camera service. Now my requirement is to keep the service running after I turn off the screen. I am acquiring PARTIAL_WAKE_LOCK too. The services run perfectly for the initial 10 or 12 minutes. After that, the app stops sending any logs to ADB. In the device, the app goes to the background by itself. Not even onPause or onDestroy is logging anything. The logs just stop coming to Android Studio. For resuming the normal functioning I have to manually open the app again,
These are the things that I have already tried,
1.Given permission of acquiring PARTIAL_WAKE_LOCK.
2.Setting android:largeHeap="true"
3.Foreground services
According to Doze mode documentation it ignores wake locks.
Also starting from Android Pie it is impossible to gain camera access from background app.
Also according to android developer guidelines you must free camera, when you app is paused, because it will block all other apps.
onSaveInstanceState function should be called in these situations, check with you and if its called then open the activity again with the delay.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(getBaseContext(), YourActivity.class);
startActivity(intent);
finish();
} catch (Exception ex) { }
}
}, 200);
}

Android Studio - Using Service to call final() vs. FLAG_ACTIVITY_NEW_TASK

I have been scouting around for a while, but cannot locate any information for calling final() using started services... or rather, when not using bound services. There is tons of info for bound services, but I already have two pretty large "started services" without binding, so I didn't want to modify the existing services more than absolutely necessary.
My app works by reading bluetooth data every 10 seconds, and depending on the data read, the Service will change to a new activity. However, I cannot call final() from my services, so I fear that I might be endlessly stacking activities while the application/services are running.
To change activities, I had to add Intent.FLAG_ACTIVITY_NEW_TASK. Considering the below image/definition from the developer's page, this flag looks like it might already handle my stacking issue? I do NOT allow for users to use the back button on their phones as everything is handled via confirm/cancel buttons and the services. My app MUST be this way for a few reasons. Thus, keeping the stack order isn't important to my application.
Key Points -
I want to ensure i'm not stacking up activities endlessly when starting new activities
Flagging "new task" when starting activities via my services
Stack order is not important to my app
Below is a very small cut of my code with comments to explain what i'm trying to do. Please make sure to look to the onDestroy() method of this service.
public class AlertService extends Service {
final class Threader implements Runnable{
// Scans bluetooth advertisement packets every 10 seconds
// Thread Runs until interrupted
// Stops service via service ID
stopSelf(this.serviceID);
}
#Override
public void onCreate(){
super.onCreate();
}
// Runs a thread until alert is found.
// Alert calls thread.interrupt()
#Override
public int onStartCommand(Intent intent, int flags, int startID){
enableBluetooth();
// Start Thread
thread = new Thread(new Threader(startID));
thread.start();
return START_STICKY;
}
#Override
public void onDestroy(){
thread.interrupt();
Intent alertActivity = new Intent(this, AlertActivity.class)
alertActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(alertActivity);
}
// Unused Method - We will not be binding
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
EDIT via recommendation to use android:taskAffinity -
Using android:taskAffinity won't help me in this situation. By default, all activities in an application have the same affinity. When I create a new task by setting Intent.FLAG_ACTIVITY_NEW_TASK in the intent flags, the new activity will STILL be started in the same task if the activity has the same taskAffinity of the root activity in the task. Since I am just using the default affinity, everything should have the normal stack flow. I just cannot call finish(), which means that I am stacking up tons of activities.
To answer my own question, each new activity called via Intent.FLAG_ACTIVITY_NEW_TASK, was creating a new instance of each activity and putting it on the stack. This is true. However, each activity is NOT making a new Task, which was one of my fears as well.
When I create a new task by setting Intent.FLAG_ACTIVITY_NEW_TASK in the intent flags, the new activity will STILL be started in the same task (not in a new task) if the new activity has the same taskAffinity of the root activity in the task. Since I am just using the default affinity, every activity I create is being put into the same task. This means that nothing is acting any differently than the normal flow of creating activities and such.
Though, since I have disable the back button for my application, these activities created by flagging a new task are not finished, destroyed, or removed from the stack. To solve this, I will use FLAG_ACTIVITY_CLEAR_TOP, which finds a running instance of an activity in the stack (if there is one) and closes all of the activities above it.
Since my application always starts with the home screen, then ends with the home screen, flagging "clear top" will always close all activities above my home screen. So, upon return to the home screen, the only item on the stack will be the home screen.
I will have to test this, but it seems that I will not call finish() from my home activity to achieve this result - Otherwise, upon returning to the home activity, not all of the stack will be cleared.

How to kill Android app 100% when hitting Back

I'm developing on a Galaxy S6 running Lollipop. I used Android Studio to create a ScrollView app using the template that comes with Android Studio. I only added the following Java code:
#Override
public void onBackPressed() {
Toast.makeText(this, "onBackPressed", Toast.LENGTH_SHORT).show();
super.onBackPressed();
}
#Override
protected void onPause() {
Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show();
super.onPause();
}
#Override
protected void onStop() {
Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show();
super.onStop();
}
#Override
protected void onDestroy() {
Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
When I tap Back on the device, all 4 toast messages come up in the sequence that they appear in the code. However, when I view the app in Application Manager, the Force Stop button is still enabled, indicating that the process is still active. To confirm that I also downloaded a third party app to view active processes and it shows mine in the list.
Is there something that has to addes so that when hitting the Back button on the device the process will die 100% and not be on that active processes list any longer?
This is expected behavior on Android.
Android makes no guarantees as to when it will kill your app when exiting, so I'm not sure why you think it's supposed to. It's more beneficial for Android to keep your app in memory as long as possible so that its's faster to resume.
Please this code in your OnBackPressed() method:
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
That way your app will be completely closed and removed from running apps.

Close app after some time in background

I'm looking for a way to close an android app after some time while the app has not been in focus. For example if the user open up an other app instead, the app should exit after 5 mins. I have tried using runnable and creating a thread. But those method don't seems to work while the app is in the background (maybe they are pause I'm not sure). So how do I close the app when it is not in focus?
For those who are wonder the reason I want to do this is that the app contains some sensitives data about the user so I want to be sure it is all cleared when they aren't using it.
Something like this might work:
A field inside activity class:
private Thread t = null;
Inside onResume():
if(t!=null) {
if(t.isAlive()) {
t.interrupt();
t.join();
}
t=null;
}
Inside onPause():
t = new Thread() {
public void run() {
try {
sleep(5*60*1000);
// Wipe your valuable data here
System.exit(0);
} catch (InterruptedException e) {
return;
}
}.start();
}
I recommend calling finish() in the onPause() or onStop() callbacks. A TimerTask will not survive onPause() and a Service does not appear, on face value, to give you options. Maybe you can start a service, sleep the thread the service runs on, then kill the processes your app has after the sleep timer expires.
Alternatively, you can just implement some security libraries to help secure the data from other apps.
Here is the Google Services link.
Get the process ID of your application, and kill that process onDestroy() method
#Override
public void onDestroy()
{
super.onDestroy();
int id= android.os.Process.myPid();
android.os.Process.killProcess(id);
}
Refer- how to close/stop running application on background android
Edit- Use this with AlarmManager
The fundamental problem with what you're trying to do is that your Activity may not exist in memory at all when it's "running" in the background. The Android framework may have destroyed the activity instance and even the process it was running in. All that exists may be the persistent state you saved in onSaveInstanceState(...) and a screenshot for the recent apps list. There may be nothing for you to get a reference to and kill.
Frank Brenyah's suggestion to call finish() in onPause() will prevent your activity from running in the background at all, but this is the closest you can get to what you want. You probably only want to do this when isChangingConfigurations() is false. But even when all your app's activities are finished, Android may keep the process and Application instance around to avoid recreating them later. So you may also want to use Bhush_techidiot's suggestion of killing the process. Do this in onPause() because the activity may be destroyed without a call to onDestroy().

Categories