I have an issue here
when I click on the exit button on my android app which I debug it with my Samsung Note 3. it will looping from the start of the app instead of exiting it to the main screen of my note 3
below is my code:
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Button start=(Button)findViewById(R.id.btnStart);
Button exit=(Button)findViewById(R.id.btnExit);
start.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
/** start game */
startLoop();
}
});
exit.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
onDestory();
}
});
}
public void startLoop(){
Intent game = new Intent(this, Splash.class);
startActivity(game);
}
protected void onDestory(){
int pid=android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
}
Just call finish() - no need to do any of the onDestroy() stuff.
finish() will close the app for you.
Furthermore, any time you override onDestroy(), make sure to call super.onDestroy()!
call finish() on your exit button's on click listener. You could also use java's System.exit(0)
This is how I handle my game...
GameWorld.java (or something else) need to take controle over the game state
public void pauseThread() {
gameLoop.setKeepPlaying(false);
}
GameLoop.java
// method for accessing the game logic
public void setKeepPlaying(boolean run) {
keepPlaying = run;
}
and the loop itself:
/** MAIN GAME LOOP */
while (keepPlaying) {
[...]
}
btw: driven is this loop by a Thread
EDIT: example which part onDestroy takes in Android....
#Override
protected void onDestroy() {
Log.d("MainActivity", "***onDestroy()***");
disableKeepScreenOn(getWindow(), TAG);
unregisterReceiverAndStopServices();
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nManager.cancel(NOTIFICATION_GENERAL);
super.onDestroy();
}
And here is a Menu, which provides one entry to close the application...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
[...]
case (OPM_EXIT):
MainActivity.this.finish();
return true;
default:
return false;
}
}
Related
I'm writing a android game. I want to click on button, all application runs of the first.
This is my code:
newgame.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
This works but when user onBackPressed, opens previous page instead of application is closed. How can i do that run my app again of the first?
You can recreate the Activity like this:
public void restartActivity() {
finish();
startActivity(getIntent());
}
And call the above method from the onClick event:
newgame.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
restartActivity();
}
});
Try doing it this way:
#Override
protected void onPause() {
/* destroy any life cycle of any sound, and voice here or
anything need to be disposed */
super.onPause();
}
#Override
public void onRestart()
{
super.onRestart();
finish();
startActivity(getIntent());
}
Good Luck...
I want to show launcher screen in Android app only once. Then if the user is on the second screen, if he presses back button, I want app to close. What's wrong in this code? The first screen shows again, what mustn't be.
public class MainActivity extends Activity {
private boolean firstscreenshown=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (firstscreenshown==true) finish();
firstscreenshown=true;
or
public class MainActivity extends Activity {
private boolean firstscreenshown;
public MainActivity() {
this.firstscreenshown = false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
if (firstscreenshown==true) finish();
firstscreenshown=true;
Use this code for handle back button in your MainActivity class:
#Override
public void onBackPressed()
{
// TODO Auto-generated method stub
super.onBackPressed();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
I have a disclaimer view that I display the first time my app is run. Here is how I handle it:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// check preferences to see if disclaimer has been display
boolean showDisclaimer = getPreferences(MODE_PRIVATE).getBoolean("disclaimer", true);
if (showDisclaimer) {
// turn off the disclaimer
getPreferences(MODE_PRIVATE).edit().putBoolean("disclaimer",false).commit();
// display the disclaimer
Intent intent = new Intent(MainActivity.this, LegalActivity.class);
startActivity(intent);
}
setContentView(R.layout.activity_main);
}
Here is the activity for the disclaimer:
public class LegalActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.legal_detail);
// Watch for guide button clicks.
Button button = (Button) this.findViewById(R.id.legal_button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
My disclaimer view has a done button which closes it.
Hope this helps!
Call finish after your call to the second activity, so when the second screen appears the previous one will be erased.
startActivity(intent)
The best and simplest way to achieve this would be to override onPause() method and call :
finish();
inside the first activity!
I know this question have been asked many times around here, but i didn't find the propert answer for my issue.
this code can disable back button:
#Override
public void onBackPressed() {
// Do Here what ever you want do on back press;
}
but is there anyway that i can disable back button for a temporary time,not for the whole Activity ?
nice answer by Dixit. Just another option
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean result = false;
if (keyCode == KEYCODE_BACK) {
if (condition) {
result = true;
}
}
return result;
}
N.B ..
it will work on ancient version also
returning true from onKeyDown consumes the default behavior
You have to set on boolean flag where you have to require disable back button set flag value true;
In onBackPressed() you have to put condition as per #Dixit says
#Override
public void onBackPressed() {
if(condition to check){
// this block disable back button
}else{
// this block enable back button
super.onBackPressed();
}
}
If you want to disable backbutton for certain time use this,
//for 5 sec = 5000
countDownTimer = new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
txtWait.setTextColor(getResources().getColor(R.color.errorcolor));
txtWait.setText("Wait( " + millisUntilFinished / 1000+" sec)");
onBackPressed();
}
#Override
public void onFinish() {
YourActivityName.super.onBackPressed();
}
}.start();
And in the override method:
#Override
public void onBackPressed() {
//super.onBackPressed(); commented this to disable the back press
}
Full working code:
YourActivity extends AppCompatActivity{
boolean isBackButtonDisabled = false;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState)
setContentView(R.layout.somelayout);
disableBackButton(4000); //<--Back button is disabled
}
#Override
public void onBackPressed(){
if(!sBackButtonDisabled){
super.onBackPressed();
}
}
private void disableBackButton(final int timeInMilis){
if(!isBackButtonDisabled) {
isBackButtonDisabled = true; //<-- Keep it outside Thread code
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(timeInMilis);
} catch (InterruptedException e) {
} finally {
isBackButtonDisabled = false;
}
}
});
t.start();
}
}
}
Note: You can use disableBackButton(time) in other scenarios as well. For example Button click. If
you click button multiple times the Thread will only run once. Because in this code
isBackButtonDisable variable is thread-safe "in a way".
i writed an application which contains an option button and Option Activity.
In the OptionActivity, you can choose play a music "on" or "off" with togglebutton. and there are some check button also.
until here everything is okey but when you check some box and back to the main menu and back to the Options Activity again, you find that all variables is default value. for example the checked box one is uncheckhed. I know that it is because of everyCall the Options Activity with new Intent but i want to know that starting an activity "without using new Intent"
This is my SPLASH SCREEN
public class MainActivity extends Activity {
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.baslangic);
Thread thred=new Thread(){
public void run(){
try {
sleep(5000);
startActivity(new Intent("com.KAYA.ingilizce_gelistirme.OPTIONS"));
startActivity(new Intent("com.KAYA.ingilizce_gelistirme.BASLANGIC"));
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
finish();
}
}
};
thred.start();
}
}
This is my MAIN ACTÄ°VTY which contains options button
public class Baslangic extends Activity {
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start=(Button)findViewById(R.id.button1);
Button options=(Button)findViewById(R.id.button2);
Button about=(Button)findViewById(R.id.button3);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent("com.KAYA.ingilizce_gelistirme.OYUN"));
}
});
options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
about.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent("com.KAYA.ingilizce_gelistirme.ABOUT"));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
And This is My options Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
it=(RadioButton)findViewById(R.id.radio0);
ti=(RadioButton)findViewById(R.id.radio1);
final ToggleButton but=(ToggleButton)findViewById(R.id.toggleButton1);
music=MediaPlayer.create(Options.this, R.raw.avril);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(but.isChecked())
music.start();
else
music.pause();
}
});
it.setChecked(true);
Button menu=(Button)findViewById(R.id.button1);
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent("com.KAYA.ingilizce_gelistirme.BASLANGIC"));
}
});
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
startActivity(new Intent("com.KAYA.ingilizce_gelistirme.BASLANGIC"));
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onStop() {
super.onStop();
}
}
NOTE: Be aware That when the user click the options Button, i call finish(), actually i have a solution. My solution that, after the splash screen, i start 2 activity; first Options later Menu, And when the user click the Options button and i call the finish() so i am in the options Button :D and when press back i called new Intent(menu) you can see on OPTIONS activity,
So my problem is already solved but i want to know that there should be a solution different from this way, If you know pls help me. :)
Are you using the PreferenceActivity or a normal Activity superclass?
Anyway, be sure to read about the SharedPreferences - it can store your values for entire app or for single activity.
I have 2 activities. One called Login and another called ListDeals. Login has a form with a submit button which, when pressed, should switch our activity to ListDeals. This works.
However, in Logcat I don't get a message saying that the activity has started. Also, when in ListDeals, if the user presses the back button, both activities should be killed. I looked around and this is what I came up with:
public class Login extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
Button submit=(Button)findViewById(R.id.submit);
submit.setOnClickListener(onSubmit);
}
private View.OnClickListener onSubmit=new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent=new Intent(view.getContext(),ListDeals.class );
startActivityForResult(myIntent,0);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login_screen, menu);
return true;
}
#Override
public void onActivityResult(int requestCode,int resultCode, Intent data) {
if(resultCode==2) {
finish();
}
}
}
public class ListDeals extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.deals_list);
System.out.println("starting activity");
}
#Override
protected void onDestroy() {
System.out.println("dude");
setResult(2);
super.onDestroy();
}
protected void onStop(){
setResult(2);
super.onStop();
}
}
However, when I press the back button, It takes me back to the Login activity which is not what I want.
In your click handler, onSubmit, just finish your login activity, like this. That way, it won't be on the activity stack, and as a result, pressing back from your other activity will bring the user back to where they started.
private View.OnClickListener onSubmit=new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent myIntent=new Intent(view.getContext(),ListDeals.class);
startActivity(myIntent);
finish();
}
};
Also, to address you second question, use the Log class methods, such as Log.i or Log.d for debug messages, those will show up in logcat.
Finish Login before starting the new Activity. Besides you don't need the result.
private View.OnClickListener onSubmit=new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent=new Intent(Login.this, ListDeals.class );
startActivity(myIntent);
Login.this.finish() // add this to finish it.
}
};