0

I am trying to prevent the HOME button KeyPress when a Service is running

protected void onPause () {
   if (isMyServiceRunning())
   {
       Intent Act2Intent = new Intent(PhysicalTheftDialog.this, PhysicalTheftDialog.class);              
       startActivity(Act2Intent);
   }
   else {

   }
}

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("nyp.android.project.MyService".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

But everytime when i press my HOME button the application crashes.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
dythe
  • 840
  • 5
  • 21
  • 45

1 Answers1

1

See, for security reasons android developers itself are not allowing us to change any kind of behaviour with home button. But even though if you really want to disable the home button press you can do this by adding below code:

@Override
public void onAttachedToWindow() {
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
    super.onAttachedToWindow();
}

@Override    
public boolean onKeyDown(int keyCode, KeyEvent event) { 
    if(keyCode == KeyEvent.KEYCODE_HOME) {
        Log.i("Home Button","Clicked");
    }

    if(keyCode==KeyEvent.KEYCODE_BACK) {

        finish();
    }
    return false;
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Daud Arfin
  • 2,499
  • 1
  • 18
  • 37