androidback-buttonback-button-control

Why is the disable back button code not working in Android?


I want to disable the back button for my android app. All I want to do is, when the user presses the back button, nothing should happen. Basically like return false in JavaScript. The following is the code that I have in my MainActivity that I am using currently:

package com.ws.gostock;

import android.os.Bundle;
import org.apache.cordova.*;

public class MainActivity extends CordovaActivity
{
   @Override
   public void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
      // Set by <content src="index.html" /> in config.xml
      loadUrl(Config.getStartUrl());
   }

   @Override
   public void onBackPressed()
   {
      System.out.println("back pressed");
   }
}

Tried to run in debug mode, What happens is, when I press the back button the app closes, and then the code starts to debug. I don't know why.


Solution

  • I fixed the problem.. here is the code that I used:

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // Set by <content src="index.html" /> in config.xml
       loadUrl(Config.getStartUrl());
       
       appView.setOnKeyListener(new View.OnKeyListener() 
       { 
           public boolean onKey(View v, int keyCode, KeyEvent event) 
           {
               if (event.getAction() == KeyEvent.ACTION_UP) 
               {
                   if(keyCode == KeyEvent.KEYCODE_BACK) 
                   {
                       if(t == null)
                       {
                           t = new Timer();
                           t.schedule(new reInitializeTimer(), 0, 1*1000);
                           Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();
                       }
                       else if(backpress >= 1)
                       {
                           finish();
                       }
                       
                       return true;
                   }
                   return onKeyUp(keyCode, event);
               }
               return onKeyDown(keyCode, event); 
           } 
      });
    }
    
    class reInitializeTimer extends TimerTask
    {
        public void run()
        {
            backpress++;
            if(backpress > 3)
            {
                backpress = 0;
                t.cancel();
                t = null;
            }
        }
    }