How to exit of program on android - java

How to exit from my app on button click in Android app?
I've tried button click event method. Tell me the code or logic for it.
java file:
Button button;
button=(Button) findViewById(R.id.exit);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});

Just make a finish(); as follows :
Button button;
button=(Button) findViewById(R.id.exit);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
What does finish() do?
Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().
For more information read the finish() documentation
EDIT
Add this on your manifest.xml file :
<activity
android:autoRemoveFromRecents="true"/>
If you want to avoid finish(); just call an Intent like this :
Intent i = new Intent(Intent.ACTION_MAIN);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
EDIT with sample
My manifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My setOnClickListener()
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(Intent.ACTION_MAIN);
intent1.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
intent1.addCategory(Intent.CATEGORY_HOME);
startActivity(intent1);
//finish(); it can also be done
}
});

#Override
public void onClick(View paramView)
{
finish();
moveTaskToBack(true);
}

In Android is not recommended to close/kill applications, because that is already done by OS automatically when needed. As #33go user already recommended, calling finish() in your application should be enough. But if you really want to stop the process in an easy way you can try this, from everywhere in your app:
System.exit(0);

try
android.os.Process.killProcess(android.os.Process.myPid());

Just try to double back press to exit your application. Paste this code to your activity:
private static long back_pressed;
#Override
public void onBackpressed()
{
if (back_pressed + 2000 > System.currentTimeMillis()) {
super.onBackPressed();
} else {
Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
}
this.back_pressed = System.currentTimeMillis();
}

Related

I would like to make a call using one button and use one fixed number

I would like to make a call using one button. The phone number should be inside. But my code is inoperative. Who can support?
public class MainActivity extends AppCompatActivity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
}
public void onClickStart(View view) {
button = findViewById(R.id.button);
((Button)findViewById(R.id.button)).setOnClickListener((View.OnClickListener) v -> {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phNum = "tel:" + "89261234567";
callIntent.setData(Uri.parse(phNum));
startActivity( callIntent) ;
});
}
}
manifest file
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.GateApp">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Your problem is that you're never assigning the click listener to the button, since onClickStart is never invoked. This is how you should do it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener((View.OnClickListener) v -> {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phNum = "tel:" + "89261234567";
callIntent.setData(Uri.parse(phNum));
startActivity( callIntent) ;
});
}
This way you're assigning the click listener to the button. In the documentation you can find how to use it.
Here it is the link at the call intent documentation
Just use this two lines of code inside onClickListener:
((Button)findViewById(R.id.button)).setOnClickListener((View.OnClickListener) v -> {
String phNum = "tel:" + "89261234567";
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phNum, null)));
});
I think you can add to manifest file this string
<data android:scheme="tel" />
// This works well!
((Button) findViewById(R.id.button1)).setOnClickListener((View.OnClickListener) v -> {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phNum = "tel:" + "87777777777";
callIntent.setData(Uri.parse(phNum));
startActivity(callIntent);
});

Android app opens after a few seconds after pressing home button during splash screen

I am having an issue I can't seem to figure out the reason for.
When you launch the app, a splash screen is first displayed for 2.5 seconds before finishing and starting a new activity. If you press the home or back button during this time the app will close as normal. However after a few seconds (longer than 2.5) the app will open and start from the activity that comes after the splash screen.
Any help on why this happens is appreciated!
Here is the implementation of the Splash screen (I do however not believe anything here causes this issue as I've tried different implementations)
`public class SplashScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
Thread myThread = new Thread(){
#Override
public void run() {
try {
sleep(2500);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
myThread.start();`
Here's the manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".activities.MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
android:launchMode = "singleInstance">
</activity>
<activity android:name=".activities.SplashScreenActivity"
android:theme="#style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".alert.BroadCaster" >
</receiver>
<service android:name=".timer.TimerService"
android:process=":timerservice" />
</application>
It happens because you are creating a new Thread and this thread will be still alive after you put your app in background. You can change your approach using an Handler. If you need that your next Activity won't start if the splash screen is in background, you have to store the current time before the delay starts.
private static final long SPLASH_SCREEN_MS = 2500;
private long mTimeBeforeDelay;
private Handler mSplashHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
// Create a new Handler.
mSplashHandler = new Handler();
}
#Override
protected void onResume() {
super.onResume();
// The first time mTimeBeforeDelay will be 0.
long gapTime = System.currentTimeMillis() - mTimeBeforeDelay;
if (gapTime > SPLASH_SCREEN_MS) {
gapTime = SPLASH_SCREEN_MS;
}
mSplashHandler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
SplashScreenActivity.this.finish();
}
}, gapTime);
// Save the time before the delay.
mTimeBeforeDelay = System.currentTimeMillis();
}
#Override
protected void onPause() {
super.onPause();
mSplashHandler.removeCallbacksAndMessages(null);
}
Just use handler instead of thread sleep like this
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
SplashScreenActivity.this.finish();
}
}, SPLASH_DURATION);
You need to implement the onStop() method, only if you want to save data and memory.

splashscreen and second activity back

I'm writing a simple app using Android studio which open main acitivity and when I click on button it make new intent in order to launch URL in web browser. The code to open URL is:
String Link=listURL.get((int) id).toString();
Uri uriUrl = Uri.parse(Link);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
It works fine, it shows the web results and I can come back to the main activity using the back button. All worked fine until I've decided to use a splash screen.
After implemented a splash screen, when I click on back button in web brower, it exit from app. It doesn't come back no more in the "main" activity.
here my manifest.xml:
If i try to remove the .splashscreen stanza, all works fine. I have'nt the splash screen but all works. Could be a manifest's properties problem?
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashScreen"
android:theme="#android:style/Theme.Translucent"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Here my splash screen:
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent intent = new Intent(SplashScreen.this,MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
thanks
Giovanni
call finish() after execution of statement causes starting MyActivity
Intent intent = new Intent(SplashScreen.this,MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
Avoid calling finish() in onPause().
delete finish() from onpause and write your timer code inside onresume it will work
Ex:
onresume()
{
Thread timerThread = new Thread(){
public void run(){
try{
sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent intent = new Intent(SplashScreen.this,MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
};
timerThread.start();
}
i think its works for you
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
after intent
finish();
Thank you for your suggestions but it didn't solved.
I've solved using another new and not predefined activity and all works fine.
Giovanni

Can't switch between activities

sorry for asking dumb questions, java and Android are both new to me ;)
My problem: I can't switch between two activities in a very simple app. I tried solutions described in similar topics but it didn't work.
So this is my 1st Activity (I didn't paste the imports):
public class OneActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void OnStart(){
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
OneActivity.this.startActivity(myIntent);
}
});
}
}
The second Activity is very simple - it is just supposed to load a layout called userinput.xml:
public class UserInput extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userinput);
}
}
The application part of the Manifest looks like following:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".OneActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<activity
android:name=".UserInput"
android:label="#string/app_name" />
</activity>
</application>
When I run the app and click the button nothing happens. Where could be the problem?
// Alright, I have put the code into the onCreate() method so it now looks like following:
public class OneActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
OneActivity.this.startActivity(myIntent);
}
});
}
}
Now the app crashes (force close) anytime I click the Next button.
You define your onStart() function with a capital 'O'. That is why the function is never called.
Your onStart():
public void OnStart(){ ... }
How it should be:
// Note the lowercase 'o' in onStart
public void onStart(){ ... }
Also note that having an #Override above the function name when you want to override a method will help prevent making these mistakes, as Eclipse (or whatever IDE you use) will tell you that you are not actually overriding a function.
Write below code in onCreate() method:
Button Btn = (Button)findViewById(R.id.btnNext);
Btn.setOnClickListener(new OnClickListener() {
public void onClick(View Button) {
Intent myIntent = new Intent(OneActivity.this, UserInput.class);
startActivity(myIntent);
}
});
2nd correction for android manifest file:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".OneActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> <!-- closed here -->
<activity
android:name=".UserInput"
android:label="#string/app_name" />
</application>
You can move all the code in onCreate() and simplify like this
startActivity(new Intent(this, UserInput.class));
But I don't understand why you start another activity like this
Check it following line
Intent myIntent = new Intent(OneAvtivity.this, SecondActivity.class);
startActivity(myIntent);
Your Class name is UserIpnout and you write SecondActivity.class
Intent myIntent = new Intent(OneAvtivity.this, UserInput .class);
startActivity(myIntent);

Unable to get Broadcast

I am unable to receive broadcast intent, although I have registered it . Can you please spot the error. Thank you very much. I tried with log messages, but it never reached onReceive() of broadcast receiver class.
Here is Class from which I send Broadcast
public class ServiceDemoActivity extends Activity {
Button startButton,stopButton,pauseButton;
final String musicIntentAction="com.CompetenceProject.Musicfilter";
Intent musicIntent=new Intent();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startButton=(Button)findViewById(R.id.startButton);
stopButton=(Button)findViewById(R.id.Stopbutton);
pauseButton=(Button)findViewById(R.id.Pausebutton);
musicIntent.setAction(musicIntentAction);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("DEBUG", "Came to StartButton");
musicIntent.putExtra("Message","start");
sendBroadcast(musicIntent);
Toast.makeText(getApplicationContext(), "starBroadcaseSent",1000).show();
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("DEBUG", "Came to StopButton");
musicIntent.putExtra("Message","stop");
sendBroadcast(musicIntent);
Toast.makeText(getApplicationContext(), "stopBroadcaseSent",1000).show();
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.w("DEBUG", "Came to PauseButton");
musicIntent.putExtra("Message","pause");
sendBroadcast(musicIntent);
Toast.makeText(getApplicationContext(), "PauseBroadcaseSent",1000).show();
}
});
}
}
Here is Class that listens to broadcast:
public class MusicBroadcsatListener extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Log.w("DEBUG", "Came to BroadCast OnRecieve");
Bundle extras = intent.getExtras();
String res=extras.getString("Message");
Toast.makeText(context, "Intent Extra is "+res, 1000).show();
Log.v("BroadCase","true");
System.out.println("Broadcast came here");
if(res.equalsIgnoreCase("start"))
Toast.makeText(context, "start", 1000).show();
else if(res.equalsIgnoreCase("pause"))
Toast.makeText(context, "pause", 1000).show();
else if (res.equalsIgnoreCase("stop"))
Toast.makeText(context, "stop", 1000).show();
}
}
This is the Androidmanifest:
<activity
android:label="#string/app_name"
android:name=".ServiceDemoActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<receiver android:name=".MusicBroadcsatListener" android:enabled="true">
<intent-filter>
<action android:name="com.CompetenceProject.Musicfilter"></action>
</intent-filter>
</receiver>
Thank you.
First thing I would do is check this typo you have in your Manifest.xml file. I can't see the name of your receiver class here, but if its name has "broadcast" in it, you spelled "broadcast" wrong -- "MusicBroadcsatListenter" -- in your manifest.xml file:
<receiver android:name=".MusicBroadcsatListener" android:enabled="true">
To test, you have to execute the broadcast receiver before you execute the activity -- on the same device -- because the receiver needs to be running. I'm not sure the best way to do this, but out of curiosity I copied and pasted your code into Eclipse into two separate projects -- one for the receiver and one for the activity. I executed the receiver project, then the activity project, and your code worked fine. If someone has a better way to test this, please post as I'd like to know too.
I found the solution by myself. I had put the receiver inside the activity tag. Thank you all for the support.

Categories