I need to finish an android application. For that i wrote
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure You want to exit")
.setCancelable(false)
.setPositiveButton("YES"),
new DialogInterface.OnClickListener() {
// On
// clicking
// "Yes"
// button
public void onClick(DialogInterface dialog,int id) {
System.out.println(" onClick ");
closeApplication(); // Close Application method called
}
})
.setNegativeButton("NO"),
new DialogInterface.OnClickListener() {
// On
// clicking
// "No"
// button
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void closeApplication() {
System.out.println("closeApplication ");
this.finish();
}
}
But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application
To close application just call:
android.os.Process.killProcess(android.os.Process.myPid());
Otherwise due-to specific life-cycling of Android activities you can't be sure that application is closed/killed.
whenever you are starting a new activity use
myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myintent);
and in manifest file mention that activity as
<activity android:name=".<Activity Name>" >
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Put this into your onClick or in onBackPressed:
moveTaskToBack(true);
finish()
Please read first this post from Google Android Developer Advocate Reto Meier :
When to Include an Exit Button in Android Apps (Hint: Never)
What is th symptom that make you want to add an exit button ? If you need to clear the activity stack and always restart with a specific Activity, maybe you just have to tweak your activity manifest declaration with attributes like : android:clearTaskOnLaunch
Android is made in such a way that virtually NO application that was once opened, is closed.
Before mis-interpreting the statement, understand this.
"Whenever you exit your app, Android saves all the things the app was doing (called its state) and pushes the app in the background, calling the onStop() method. this is the new state of the application then, where the app isn't running, but isn't flushed out of the memory too. whenever you start the app again, it is resumed from the frozen state. Only when the memory, where frozen apps are kept, starts getting full, the Android GC flushes the app."
So conceptually, nothing goes out. when you hit "back" button while ur on the first activity, Android bundles the app and data, and freezes it.
according to this answer,
just write this.finishAffinity(); and done!
I have an application with several Activities. I extended my Application class, and included a variable numActive. This is initialized to 0. Within each activity's onStart(), numActive is incremented, and in onStop() it is decremented. If the count reaches zero, the user has left my application entirely, and I close down my background tasks.
Shameless copy of NeTeInStEiN's answer as I found it so useful (please up-vote his answer): Sending a running application to background programmatically
You can use either:
boolean sentAppToBackground = moveTaskToBack(true);
if(!sentAppToBackground){
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
}
More information here: http://developer.android.com/reference/android/app/Activity.html#moveTaskToBack(boolean)
Or simply:
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
According to Romain Guy a Android Framework Engineer, "You cannot simulate a press on the Home key.". So beware...
Check: http://osdir.com/ml/Android-Developers/2010-03/msg01887.html
Updated this answer according to: moveTaskToBack(true) returns false always
To Close the Application, you can also take "System.exit(0)" 0 is standard or use any exit code.
Related
Some services vary between Android and iPhone, for example floating widget, widget on the home screen, can I make them using flutter
Can I view a dialog on the home screen like this example?
update
thank everyone answer, but I need how to get it in Flutter
Yes you can show that
new AlertDialog.Builder(YourActivity.this)
.setTitle("Alert")
.setMessage("Alert Message")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Here you can do whatever you want to do on click
}
}).show();
Sorry you can't do it in iOS, however in Android, you can, all you need to do is write platform specific code.
You could create an Activity with the Theme.Dialog theme. In your AndroidManifest.xml file add the theme to the activity, like this:
<activity android:name=".DialogActivity" android:theme="#android:style/Theme.Dialog"></activity>
From your service simply start this Activity. You will have to start the activity with the Intent.FLAG_ACTIVITY_NEW_TASK flag. See How to start an Activity from a Service
Source
This is very strange - I'm trying to programmatically open another app.
I found this link which I followed : Stackoverflow link
So my code is as follows - note it is being run inside a dialog.
Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
intentToResolve.addCategory(Intent.CATEGORY_HOME);
intentToResolve.setPackage("com.android.launcher3");
intentToResolve.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
ResolveInfo ri = getPackageManager().resolveActivity(intentToResolve, 0);
if (ri != null)
{
Intent intent = new Intent(intentToResolve);
intent.setClassName(ri.activityInfo.applicationInfo.packageName, ri.activityInfo.name);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
This seems to only "close" my app and go to the home screen if I put a breakpoint in the code. If I just let it run with no breakpoint then nothing happens.
I have no idea why it would do this? Any ideas?
Thanks.
Edit: I've uploaded a video of it happening to YouTube so you can see exactly what I mean.
You'll see the first time I run it, it hits the breakpoint and the device goes to the home screen.
The second time I run it I have removed the breakpoint and nothing happens.
YouTube link
The fact that it works if you set a breakpoint would seem to indicate that there's some sort of timing problem.
You mention that you run this code from inside a dialog, which to me, reinforces the idea that you have a timing issue.
Try running this code from the Activity, after the dialog is closed.
I'd be very surprised if that doesn't fix the issue.
I assume that you are using the dialog to let the user pick what to launch.
So, instead of attempting to launch the other app from the dialog, communicate that info to it's parent activity, and have the Activity run this code after the dialog is closed.
When you show the dialog, you are doing so from an Activity - the dialog is displayed on top of your activity.
You are probably using a Dialog Builder to build the dialog, and then calling builder.create() to show the dialog.
In the builder code, you probably do something like:
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK
}
})
In the onClick handler, the second parameter is the id of the item that was clicked. Use this info to decide what you want to launch. I'd suggest a separate method in the Activity to do the launching, and then call that from the onClick handler.
First thing is make sure do you have the app which belongs to ri.activityInfo.applicationInfo.packageName packagename. Code looks fine, the problem is the package name and the class you give inside setClassName()
I am doing one application here I have one exit button when I click button,that time I need to exit from application..I tried using below code app is closing but it still running in taslmanager..but when I click exit button I should close app as well as I should remove from task manager how it's possible.
public class MainMenu extends Activity {
Button exit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
exit=(Button)findViewById(R.id.btn1);
exit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
try this to exit the application
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
finish();
Please think really hard about if you do need to kill the application: why not let the OS figure out where and when to free the resources?
Otherwise, if you're absolutely really sure, use
finish();
As a reaction to #dave appleton's comment: First thing read the big question/answer combo #gabriel posted: Quitting an application - is that frowned upon?
Now assuming we have that, the question here still has an answer,
being that the code you need if you are doing anything with quitting
is finish(). Obviously you can have more than one activity etc etc,
but that's not the point. Lets run by some of the use-cases
You want to let the user quit everything because of memory usage and
"not running in the background? Doubtfull. Let the user stop certain
activities in the background, but let the OS kill any unneeded
recourses. You want a user to not go to the previous activity of your
app? Well, either configure it so it doesn't, or you need an extra
option. If most of the time the back=previous-activity works,
wouldn't the user just press home if he/she wants to do something
else? If you need some sort of reset, you can find out if/how/etc
your application was quit, and if your activity gets focus again you
can take action on that, showing a fresh screen instead of restarting
where you were. So in the end, ofcourse, finish() doesn't kill
everthing, but it is still the tool you need I think. If there is a
usecase for "kill all activities", I haven't found it yet
Use this flag:
FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS.
This flag will notify the OS to remove this app/activity from the cache of recent apps.
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
You can also add
android:noHistory="true"
android:excludeFromRecents="true"
in your AndroidManifest file for the activity where you don't want to see in recent apps.
Android doesn't allow you to directly exit from the app.you just have to remove the your current activty from the stack before going to any new activity.
class first extends activity{
oncreate(){
Intent i = new Intent(getappcontext(),nextactivity);
stratactivity(i);
first.this.finish();
}
}
i want to close my whole application. i have tried out finishActivity() on back press but it doesn't work. I want to close my application on back press event completely. How could i do it?
public void onImageViewClicked(View view){
switch(view.getId()){
case R.id.viewStk:
intent = new Intent(MainActivity.this,ViewStkActivity.class);
startActivityForResult(intent, 12);
break;
case R.id.about:
Intent aboutIntent = new Intent(MainActivity.this,AboutActivity.class);
startActivity(aboutIntent);
break;
}
}
I use:
#Override
public void onDestroy()
{
super.onDestroy();
// Force the process to be killed on finish(), not kept around
System.runFinalizersOnExit(true);
System.exit(0);
}
which is called after using this.finish()
(This is an overridden method of the activity)
People will complain and tell you it breaks the Android app lifecycle, but having an "exit" button on my app during development was an immediate boost of my productivity.
Edit
Apparently, the latest version of the API notes that the runFinalizersOnExit function is deprecated and unsafe. I've had no issue with it on Gingerbread, ICS, or JB. But in interest of full disclosure, I'll point this out.
public void onClick(View v) {
finish();
android.os.Process.killProcess(android.os.Process.myPid());
}
This will also help
Intent i = new Intent(yourScreen.this,Home.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("EXIT", true);
startActivity(i);
and in the onCreate of the Home class, do this to check,
if (getIntent().getBooleanExtra("EXIT", false))
{
finish();
}
what this will essentially do is no matter at what activity you are, you can call the home screen with the clear top flag. In the home screen there is a check condition in the onCreate method which will help to clear the stack..Now ,if you press back button you will exit the app as the stack is cleared..
Let me know if the problem still persists...
In the activity.java-file that needs the implementation (fx MainActivity.java) insert this:
public void exitProgram(View view){
finish();
System.exit(0);
}
Just remember to also call the function in your .xml file, fx:
<Button
...
...
android:onClick="exitProgram"
...
/>
and finally in the buttons attributes, at the "text" attribute - press the small button next to the field and choose the one for the button you want to work with - done.
A good way to do it? No. Not at all. But if you just want a "panic-lets-get-outta-here"-button, then here you go.
There are a ton of different ways to implement the exit-functionality (one of them shown here) - as there are a ton of ways to implement the simple "Hello World" program - each has their value and you should really consider, why you have chosen the one you have.
I want to create an activity that stays always on top (like the modal windows or task manager in Windows) of the others activities.
How can I do this on Android? Thanks
You can use the following code in the overridden onStop method of your activity:
#Override
protected void onStop(){
super.onStop();
Intent intent = new Intent(this, ClassNameOfYourActivity.class);
startActivity(intent);
}
Beauty problem: your activity will pop-up again if any other activity trying to claim the focus. So it's not a modal window.
And it's dangerous! You wont be able to handle the Android GUI, you'll be able to control only your application GUI. For instance, switching debug mode on-off, killing application (only over ADB), reaching system settings, etc. will be impossible. If you switch off the ADB and combine it with the auto start mechanism then you'll be in trap.
So you won't be popular if you share it with Play :)
Depending on what exactly you are trying to do, you might be happy with windows that stay on top of other Activities.
Apps like Super Video client & Floating Notes are able to display floating windows above other activities. These questions might point you in the right direction:
Creating a system overlay window (always on top)
How to create always-top fullscreen overlay activity in Android
You can't. As this is defined in the Android system.
Follow the steps to achieve your requirement
Create an activity which is going to be the top activity
Add the following code in the manifest
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Use the following code to get overlay permission from user
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
new AlertDialog.Builder(this)
.setTitle("Permission Request")
.setMessage("This app needs your permission to overlay the system apps")
.setPositiveButton("Open settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
startActivityForResult(myIntent, 101);
}
})
.setNegativeButton(android.R.string.no, null)
.show();
}
}