Android Oreo JobIntentService Keep running in background for Android 7 &below and crashing often in Android 8 & above

前端 未结 3 721
野趣味
野趣味 2021-02-06 09:50

I have recently replaced all my service to foreground services and JobIntentService since there are some background execution limits (https://developer.android.com/about/version

3条回答
  •  孤城傲影
    2021-02-06 10:24

    I think you just need this much of a code. Create a new Class MyJobIntentService and write this much of a code and call postData() to start your service.

    public class MyJobIntentService extends JobIntentService {
    
    public static void postData(Context context, String data) {
        final Intent intent = new Intent(context, MyJobIntentService.class);
        intent.setAction(INITIAL_ACTION);
        intent.putExtra(SAMPLE_ID, data);
        enqueueWork(context, MyJobIntentService.class, 1000, intent);
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public void onDestroy() {
        Ln.d("Cancelled service");
        super.onDestroy();
    }
    
    @Override
        protected void onHandleWork(@NonNull Intent intent) {
            if (intent != null) {
                final SampleRequest sampleRequest = requests.get(intent.getAction());
                if (sampleRequest != null) {
                    try {
                       // perform some networking operations
                    } catch (Exception ex) {
                        Log.d("Error for intent ");
                    }
                    Log.i("send action ");
                } else {                
                   Log.e("action not found for ");
                }
            }
        }
    }
    

    And make sure to add your service in manifest file

    
    

提交回复
热议问题