-3

Is there a way to tell my app to do something while it's running in the Background? What i try to do is to send a sms when i press the Power Button. This is what i wrote and it works currently while i'm inside the app:

  public boolean onKeyDown(int keyCode, KeyEvent event) {
    startService(new Intent(this, BackgroundService.class));
        if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNo, null, "Ich brauche Hilfe! Hier ist mein aktueller Standort, kannst du mir helfen kommen?" + "\n" + "http://maps.google.com/?q=" + lat + "," + lon, null, null);
            return true;
        }
    return super.onKeyDown(keyCode, event);
}
bfmv991
  • 109
  • 1
  • 12
  • By means of writing a service, means keep the things which you want to run in background, in that thread. Here in the code, it seems that you have just started the service and the task you want to achieve is not kept in it. – darthvading Nov 06 '15 at 15:30

1 Answers1

1

When your app is not visible it isn't "running in the background." It's in a dormant state waiting to be restored or released. To have it explicitly perform some operation while it is in this state, you need to set up a background service that will run independently from your app. To get started, check out this Google guide: http://developer.android.com/guide/components/services.html

NoChinDeluxe
  • 3,446
  • 1
  • 16
  • 29
  • i created a background service and declared it in my manifest file: Can you check my edited code and tell me if i call it the right way? do i need to write the keyevent inside the service? – bfmv991 Nov 06 '15 at 15:20