My main activity has a button which launches UnityActivity. I need to finish the UnityActivity and return to previous activity. When pressing the back button it closes the whole application.
What can I do? Thank you!
Edit:
I use the AR player from Qualcomm Augmented Reality (Unity Extension).
I have only one main activity which I start the AR player from Qualcomm Augmented Reality.
Main Activity
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onBtnStartClick(final View v) {
Intent i= new Intent(this,ArPart.class);
startActivity(i);
}
}
AR Player Activity
public class ArPart extends QCARPlayerActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
}
return super.onKeyDown(keyCode, event);
}
}
I found it easiest to use the overridden onBackPressed() but to do that you also have to make a change in your Unity project:
void Update ()
{
if (Input.GetKeyUp (KeyCode.Escape)) {
AndroidJavaClass jc = new AndroidJavaClass ("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject> ("currentActivity");
jo.Call ("onBackPressed");
}
}
Then, in your activity class:
#Override
public void onBackPressed() {
// Handle the activity however you want,
// what you do here will be executed when the back button is pressed
}
Also, remember that for this to work as expected, the UnityPlayer object cannot be paused - you should pause it after you've handled the back button press event.
Credit goes to #Frank Nguyen from this thread: Can't pass back event from Unity to android library jar.
use the following code
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
//super.onBackPressed();
finish();
}
do something like this as follows:
Intent i=new Intent(unityActivity.this,mainActivity.class); // the names of activity as per you program.
startActivity(i);
finish();
Related
Im working on offline login based application using SQLite. For the purpose of security i need to move to login activity if the app has minimized. i tried this code in onPause function
#Override
protected void onPause() {
Intent intent = new Intent(dashboard.this, login.class);
startActivity(intent);
finish();
super.onPause();
}
when i try to move from that activity to another also it moves to the login activity. i hope when im moving to another activity current activity is set to paused. that's why it moves to login activity.
you must set a Boolean to handle loginActivity ;
boolean mustGoToLoginActivity=true;
when you want to go to another Activity first set this boolean to false for example :
public void goToAnotherActivity(){
mustGoToLoginActivity=false;
//...
startActivity(anotherActivity);
}
and in onResume() methode set taht to true .
then in onPause() method :
#Override
protected void onPause() {
if(mustGoToLoginActivity){
Intent intent = new Intent(dashboard.this, login.class);
startActivity(intent);
finish();
}
super.onPause();
}
You are right, this scenario will not work. What you can do is use a static boolean to achieve the behavior like this.
public class MainActivity extends AppCompatActivity {
static Boolean navigateToLogin =false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (navigateToLogin) {
move();
navigateToLogin =false;
}
}
private void move() {
Intent intent = new Intent(this, newActivity.class);
startActivity(intent);
}
#Override
protected void onPause() {
super.onPause();
navigateToLogin = true;
}
}
In my application I am facing this issue where an activity(ex:Activity_B) is getting closed only when back button is pressed twice.I want Activity_B to close when back button is pressed once and Activity_A to display after that.
I tried this code:
public override void OnBackPressed()
{
base.OnBackPressed();
//MoveTaskToBack(true);
this.Finish();
Finish();
FinishAndRemoveTask();
}
But the behaviour is still same.
I tried putting debugger point and see how it behaves.
The Activity_B is getting called when back button is pressed.
The code to start Activity_B is :
private void OnDataLayout_Click(object sender, EventArgs e)
{
Intent intent = new Intent(this, typeof(Activity_B));
StartActivity(intent);
}
Any help is much appreciated.
Update1: I observed that the OnDataLayout_Click event is also getting called twice and after navigating to OnCreate () of Activity_B, the OnCreate() is also getting called twice.
OnDataLayout_Click event is also getting called twice
If your Button's click event was bound twice, the click event will be called twice.
Like below code:
public class MainActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
initView();
}
protected override void OnResume()
{
base.OnResume();
initView();
}
private void initView()
{
Button bt = FindViewById<Button>(Resource.Id.bt);
bt.Click += Bt_Click;
}
private void Bt_Click(object sender, System.EventArgs e)
{
Intent intent = new Intent(this, typeof(Activity1));
StartActivity(intent);
}
}
The initView method was called twice, OnCreate and OnResume method. This will cause your problem.
But, if you use SetOnClickListener method, the problem will disappear:
public class MainActivity : AppCompatActivity,View.IOnClickListener
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
initView();
}
protected override void OnResume()
{
base.OnResume();
initView();
}
private void initView()
{
Button bt = FindViewById<Button>(Resource.Id.bt);
bt.SetOnClickListener(this);
}
public void OnClick(View v)
{
Intent intent = new Intent(this, typeof(Activity1));
StartActivity(intent);
}
}
If you want to go back to Activity A from Activity B onBackpressed you need not need to write any code for backpressed but if you want to exit on Backprssed from Activity B without going to Activity A then you need to finish() it in Activity A();
I have a couple of activities that extends from a custom class I wrote which in turn extends from Activity. I've named this class LoginFinisherActivity and on overriden its onCreate function like this
private BroadcastReceiver finishReceiver = null;
public static final String ACTION_FINISH_LOGIN = "ACTION_FINISH_LOGIN";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("LoginFinisherActivity", "onCreate() called.");
finishReceiver = new FinishReceiver();
registerReceiver(finishReceiver, new IntentFilter(ACTION_FINISH_LOGIN));
}
Now the activities that extended LoginFinisherActivity are the ones that need to retain their states whenever I click the system's back button. i.e. I'm at a welcome activity and I want to go to and forth to a sign up/sign in activities. But when I either sign in or sign up, I land on NavigationActivity which extends Activity, i.e. it needs to be closed down not gone back to whichever activity it came from.
I was able to do that if I removed the onPause and onResume functions from the LoginFinisherActivity.
My FinishReceiver's code is as follows:
private final class FinishReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_FINISH_LOGIN)) {
finish();
}
}
}
Thank you for your help in advance.
Edit: following are the overriden onPause and onResume functions in the LoginFinisherActivity
#Override
protected void onPause() {
Log.d("LoginFinisherActivity", "onPaused() called.");
super.onPause();
if(finishReceiver != null) {
unregisterReceiver(finishReceiver);
finishReceiver = null;
}
}
#Override
protected void onResume(Context context, Intent intent) {
Log.d("LoginFinisherActivity", "onResume() called.");
super.onResume();
if (intent.getAction().equals(ACTION_FINISH_LOGIN)) {
finish();
}
else {
if(finishReceiver == null)
registerReceiver(finishReceiver, new IntentFilter(ACTION_FINISH_LOGIN));
}
}
Assuming you want to finish your activities on successful login/register, I think the best approach would be using startActivityForResult(Intent intent, int REQUEST_CODE) instead of handling more intents that make the flow more complex.
You can also make use of android.support.v4.content.IntentCompatIntentCompat.makeRestartActivityTask(...) if you want to terminate the previous stack of activities.
Hope it helps.
I want to end the whole application when user click back button in android.Currently It again go to previous opened activity.
I also try override onBackPressed() but it doesnt work.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
enter code here
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
return;
}
Try this, start your application from a Activity that will act as your Root.
public class Root extends Activity {
public void onCreate() {
super.onCreate();
handleIntent();
}
public void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent();
}
private void handleIntent() {
boolean end = getIntent.getBooleanExtra("End");
if (end) {
finish();
} else {
Intent intent = new Intent(this, MyRealFirstActivity.class); // where this is the class that you want the user to see when they launch your app.
startActivity(intent);
}
}
public void onResume() {
super.onResume();
finish();
}
}
Then inside the activity that you want the back button to end the app, do the following:
public class LastActivity extends Activity {
public void onBackPressed() {
Intent intent = new Intent(this, Root.class);
intent.putExtra("End", true);
intent.addFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
This way all the activities that were started in between you launching the app and then hitting the back button, will all be finished() for you. This essentially will clean the slate of the app from start to finish and then exit.
In this case you need to finish activity, so your current activity will be closed by using finish() method. but you should also write finish() in each and every previous activities, where you call intent(start another activity). Hope it makes clear.
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.finish();
startActivity(intent);
}
Here we have two methods to finish or kill the app on back button pressed.
Using finish() which closes or finishes the current activity on android screen.
for example : you have 2 activities i.e A & B. You ll go from A activity to B activity using intent, now foreground acitivity is B, you want to go back & kill B activity & goto A acitivity use finish() onclick of backbutton. If your on A activity then it closes the app. see below code.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
}
return super.onKeyDown(keyCode, event);
}
Using android.os.Process.killProcess(android.os.Process.myPid()); which kills the app i.e force close the app & goto the home screen.see below code.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Kills & force closes the app
android.os.Process.killProcess(android.os.Process.myPid());
}
return super.onKeyDown(keyCode, event);
}
Here's the way I did it in my app: ActivityA is the first one to start; it in turn starts ActivityB. In ActivityB I may encounter an error, in which case I Want to return to activityA, or everything may finish correctly, in which case I want to "finish" the app altogether.
In ActivityA:
public class ActivityA extends Activity {
...
private final static int REQUEST_ACT_B = 1;
...
private void startChild() {
startActivityForResult(new Intent(this, ActivityB.class), REQUEST_ACT_B;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_TASK && resultCode == ActivityB.RESULT_OK) {
this.finish();
}
}
}
And then in ActivityB:
public class ActivityB extends Activity {
...
public final static int RESULT_OK = 1;
public final static int RESULT_ERROR = 2;
...
private void finishWithError() {
setResult(RESULT_ERROR);
finish();
}
private void finishSuccessfully() {
setResult(RESULT_OK);
}
}
Essentially, ActivityA starts ActivityB and expects a result back. If it receives back result "OK", then it closes itself and the user is none the wiser: the app has finished. If it received result "error", then ActivityA stays open.
I have an application in which I have different activities. In 1 activity, I want that when the user presses the back button, I want the application to be closed and home screen is displayed
Code
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//Handle the back button
if(keyCode == KeyEvent.KEYCODE_BACK)
{
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage("Really Exit ?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
})
.setNegativeButton("No", null)
.show();
return true;
}
else
{
return super.onKeyDown(keyCode, event);
}
}
When I run this and press the back button, the home screen is displayed, but when I run it for the second time, I get a console output as
ActivityManager: Warning: Activity not started, its current task has been brought to the front.
And the activity in which the back button is pressed gets displayed.
I think the application does not get killed and runs in background. Just to mention, this is not the starting activity of my application.
Can somebody help me, I am beginner.
Try this code :
#Override
public void onBackPressed()
{
moveTaskToBack(true);
}
Also check this Link
For each and every Intent you have used for going into other activity u have to follow this way for passing intent just pass flag to each intent as given below and after starting Activity using startActivity() u have to add finish() after that demo code as given below
Intent i=new Intent(firstActivity.this,secondActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
You cannot kill your application at your will. The android OS will do it when it wishes to free the resources allocated to it. You cannot actually implement the exit application concept in android. The user can simply navigate away from your Activity and return to it. If it has to be restarted from the first Activity or resumed where it left, is upto the android OS, not you.
Read this post to understand the philosophy of how android apps should be designed and why you wouldn't want to exit at your will:
Is quitting an application frowned upon?
Add finish(); after that line startActivity(intent) it finish your activity.
Thanks
you need to include this class as such in your code.........
public abstract class AppBaseActivity extends Activity {
public static final String FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION = "com.hrupin.FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION";
private BaseActivityReceiver baseActivityReceiver = new BaseActivityReceiver();
public static final IntentFilter INTENT_FILTER = createIntentFilter();
private static IntentFilter createIntentFilter(){
IntentFilter filter = new IntentFilter();
filter.addAction(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION);
return filter;
}
protected void registerBaseActivityReceiver() {
registerReceiver(baseActivityReceiver, INTENT_FILTER);
}
protected void unRegisterBaseActivityReceiver() {
unregisterReceiver(baseActivityReceiver);
}
public class BaseActivityReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION)){
finish();
}
}
}
protected void closeAllActivities(){
sendBroadcast(new Intent(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION));
}
}
Then you need to extend all other classes from this class just as in an example below:
public class FirstActivity extends AppBaseActivity implements OnClickListener {
/** Called when the activity is first created. */
private Button buttonOpenNextActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
registerBaseActivityReceiver();
buttonOpenNextActivity = (Button)findViewById(R.id.buttonOpenNextActivity);
buttonOpenNextActivity.setOnClickListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
unRegisterBaseActivityReceiver();
}
#Override
public void onClick(View v) {
/* OPEN SECOND ACTIVITY.*/
startActivity(new Intent(this, SecondActivity.class));
}
}
Another class:
public class SecondActivity extends AppBaseActivity implements OnClickListener {
private Button buttonOpenNextActivity;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
registerBaseActivityReceiver();
buttonOpenNextActivity = (Button)findViewById(R.id.buttonOpenNextActivity);
buttonOpenNextActivity.setOnClickListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
unRegisterBaseActivityReceiver();
}
#Override
public void onClick(View v) {
/* OPEN THIRD ACTIVITY.*/
startActivity(new Intent(this, ThirdActivity.class));
}
}
Last Class:
public class ThirdActivity extends AppBaseActivity implements OnClickListener {
private Button buttonCloseAllActivities;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
registerBaseActivityReceiver();
buttonCloseAllActivities = (Button)findViewById(R.id.buttonCloseAllActivities);
buttonCloseAllActivities.setOnClickListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
unRegisterBaseActivityReceiver();
}
#Override
protected void onBackPressed() {
closeAllActivities();
super.onBackPressed();
}
}
Now when you press back button in third activity all other activities will also be finished altogether.
1/ dont forget to register the reciever in onCreate and unregister() it in ondestroy().
Your question is not clear dear.
As per my knowledge you should use broadCast Reciever for finishing the application and passing the intent to home Screen.
MoreOver Warning is nothing , before running your application just press Enter in your code or give sm space and den save it and re- run you appication.It will work fine....
if you want to exit your application on back press then you have to finish all the previous activities when you press the back button on that screen for this you should use the concept of BROADCAST RECIEVER ...... means you have broadcast an intent on that back press which will finish all the previous activities.