Khurshid Abbas Khurshid Abbas - 3 months ago 23
Android Question

How to keep running an IntentService even when Home button is pressed

I'm stuck with a strange problem, when I minimize my app (press home button) my

IntentService
stops. There is a while loop in the
IntentService
, it runs fine in the
IntentService
till app is running in foreground.

IntentService
class is as follows:

public class MainService extends IntentService {

public MainService() {
super("MainService");
}

@Override
protected void onHandleIntent(Intent intent) {
try {
Instrumentation inst = new Instrumentation();

while (true) {
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_VOLUME_DOWN);
}
} catch(Exception e){
e.printStackTrace();
}
}
}


And called it from my
Activity
class as:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void mainButtonClick(View view) {
Intent intentX = new Intent(this, MainService.class);
this.startService(intentX);
}
}

Answer

Did you check your logs? This is not problem with IntentService it is problem that you don't have permission to change volume after you left the app. It should crashing with:

W/System.err: java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission

You need to be system application to use this permission so this is not possible on regular Android devices.