Android使用JobIntentService

项目要上一个应用小组件,组件内容需要定时刷新,刷新任务可能会有一些耗时操作。

JobIntentService是Android 8.0 新加入的类,它也是继承自Service,根据官方的解释:

大致是说JobIntentService用于执行加入到队列中的任务。对Android 8.0及以上的系统,JobIntentService的任务将被分发到JobScheduler.enqueue执行,对于8.0以下的系统,任务仍旧会使用Context.startService执行。

 JobIntentService具体使用起来非常简单,它已经封装了大量的内部逻辑,只需要调用enqueue()就可以了。

AndroidManifest.xml

依赖项:
compileOnly 'androidx.appcompat:appcompat:1.0.0'
public class WidgetJobIntentService extends JobIntentService {
    /**
     * 这个Service 唯一的id
     */
    private static final int JOB_ID = 10111;
    private static final String  TAG = "WidgetJobIntentService";
    private SimpleDateFormat mFormat = new SimpleDateFormat("MM-dd HH:mm:ss");
    /**
     * Convenience method for enqueuing work in to this service.
     */
    static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, WidgetJobIntentService.class, JOB_ID, work);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        String workType = intent.getStringExtra("work");
        boolean empty = intent.getBooleanExtra("empty",false);
        if(workType != null && workType.equals("Refresh")){
            updateWidget(WidgetJobIntentService.this,empty);
        }
        return;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void updateWidget(Context context,boolean empty) {
        if(mFormat == null)
            return;
        //通过 RemoteViews 加载布局文件
        //通过 setTextView 等方法实现对控件的控制
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
        long millis = System.currentTimeMillis();
        String format = mFormat.format(new Date(millis));
        remoteViews.setTextViewText(R.id.widget_time, format);
        if(empty){
            remoteViews.setViewVisibility(R.id.listview, View.GONE);
            remoteViews.setViewVisibility(R.id.empty_view, View.VISIBLE);
        }else{
            remoteViews.setViewVisibility(R.id.listview, View.VISIBLE);
            remoteViews.setViewVisibility(R.id.empty_view, View.GONE);
        }

        ComponentName componentName = new ComponentName(this, NewAppWidget.class);

        AppWidgetManager widgetManager = AppWidgetManager.getInstance(context);
        widgetManager.notifyAppWidgetViewDataChanged(widgetManager.getAppWidgetIds(componentName),
                R.id.gridview);
        widgetManager.notifyAppWidgetViewDataChanged(widgetManager.getAppWidgetIds(componentName),
                R.id.listview);

        AppWidgetManager.getInstance(this).updateAppWidget(componentName, remoteViews);
    }
}

调用:

Intent workIntent = new Intent();
workIntent.putExtra("work","Refresh");
workIntent.putExtra("empty",flag);
WidgetJobIntentService.enqueueWork(context,workIntent);

你可能感兴趣的:(android)