• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.launcher3.util;
17 
18 import android.database.ContentObserver;
19 import android.net.Uri;
20 import android.os.Handler;
21 import android.os.Looper;
22 
23 import androidx.annotation.WorkerThread;
24 
25 import java.util.function.Consumer;
26 
27 /**
28  * Utility class to define an object which does most of it's processing on a
29  * dedicated background thread.
30  */
31 public abstract class BgObjectWithLooper {
32 
33     /**
34      * Start initialization of the object
35      */
initializeInBackground(String threadName)36     public final void initializeInBackground(String threadName) {
37         new Thread(this::runOnThread, threadName).start();
38     }
39 
runOnThread()40     private void runOnThread() {
41         Looper.prepare();
42         onInitialized(Looper.myLooper());
43         Looper.loop();
44     }
45 
46     /**
47      * Called on the background thread to handle initialization
48      */
49     @WorkerThread
onInitialized(Looper looper)50     protected abstract void onInitialized(Looper looper);
51 
52     /**
53      * Helper method to create a content provider
54      */
newContentObserver(Handler handler, Consumer<Uri> command)55     protected static ContentObserver newContentObserver(Handler handler, Consumer<Uri> command) {
56         return new ContentObserver(handler) {
57             @Override
58             public void onChange(boolean selfChange, Uri uri) {
59                 command.accept(uri);
60             }
61         };
62     }
63 }
64