Android JobIntentService

package zhang.phil;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.JobIntentService;

public class DemoService extends JobIntentService {
    public static final String TAG = "后台服务";

    private final static int jobId = 0xa001;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
    }

    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, DemoService.class, jobId, work);
    }

    @Override
    protected void onHandleWork(Intent intent) {
        String s = intent.getStringExtra(TAG);
        for (int i = 0; i < 3; i++) {
            SystemClock.sleep(5000);
            Log.d(TAG, Thread.currentThread().getId()+":"+s + "->" + i);
        }

        toast("任务结束");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }

    private final Handler mHandler = new Handler();

    private void toast(final CharSequence text) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(DemoService.this, text, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

需要在Androidmanifest.xml定义服务:

上层使用:

package zhang.phil;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d(DemoService.TAG, Thread.currentThread().getId() + ",MainActivity线程id");

        Intent intent = new Intent();
        intent.putExtra(DemoService.TAG, "zhangphil");
        DemoService.enqueueWork(this, intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(DemoService.TAG, "onDestroy,MainActivity");
    }
}

 

 

《Android JobScheduler 、JobScheduler》https://blog.csdn.net/zhangphil/article/details/97403956

 

《Android任务调度JobScheduler,JobService》https://blog.csdn.net/zhangphil/article/details/93621525

你可能感兴趣的:(Android,android)