Service crashing and restarting

前端 未结 3 1324
無奈伤痛
無奈伤痛 2020-12-06 08:30

There are several questions about it but I always read the same thing: \"the service will be killed if the system need resources\" or \"you can\'t build an service that runs

3条回答
  •  日久生厌
    2020-12-06 09:18

    I finally found the solution ! I removed the AlarmManager from the Service and the service does not cashed anymore, but I have to use it

    The problem is the service crash after the user swype away the app from Recent App, so what I did was prevent the app to appear in that window. Add the following to your AndroidManifest.xml as a child of

    android:excludeFromRecents="true"
    

    Now when the user exit from your app it wil not appear in the recent apps window, what means the system kills the Activity right after you exit it, so it'll not waste any resources.

    PS: don't forget to set the service to run in a separate process, add the following to your AndroidManifest.xml, as a child of

    android:process=":remote"
    

    EDIT - REAL SOLUTION FOUND

    After a lot of research and study (months of study) I took a deep look at android APIs and here is what a found, this is na expected behaviour that occours only at API 16+, a change at android arquiteture changed the way that PendingIntents are broadcasted by the system, so Google added the flag FLAG_RECEIVER_FOREGROUND, you must pass this flag to the intent you are using as a parameter on the PendingIntent.getBroadcast(), here is na example:

    if(Build.VERSION.SDK_INT >= 16)     //The flag we used here was only added at API 16    
        myIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        //use myIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); if you want to add more than one flag to this intent;
    
    
    
    PendingIntent pi = PendingIntent.getBroadcast(context, 1, myIntent, 0); // the requestCode must be different from 0, in this case I used 1;
    

    Android versions older than API 16 will work as expected, the service won't crash if you swype away the app from Recent Apps page.

提交回复
热议问题