当前位置:   article > 正文

android JeckPack官方文档学习_jetpack中文文档

jetpack中文文档

1.简介

androidx 命名空间包含 Android Jetpack 库

android.support :版本 28.0.0最后一个版本

Jetpack 库在 androidx 命名空间中发布

1.1 使用:

在项目中使用 androidx 库:

gradle.properties中

android.useAndroidX true

android.enableJetifier true 通过重写其二进制文件来自动迁移现有的第三方库

1.2 在项目中使用Jetpack 库:

settings.gradle:

  1. dependencyResolutionManagement {
  2. repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
  3. repositories {
  4. google()
  5. jcenter()
  6. }
  7. }

build.gradle 

  1. dependencies {
  2.     val lifecycle_version = "2.2.0"
  3.     implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version")
  4.     implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
  5.     ...
  6. }

1.3 JetPack库:

activity ads annotation appcompat appsearch arch.core asynclayoutinflater autofill

benchmark biometric browser

car-app camera(*) cardview collection compose compose.animation compose.material  compose.material3 compose.runtime compose.ui

concurrent constrainlayout contentpaper coordinatorlayout core cursoradapter customview databinding datastore

documentfile draganddrop drawerlayout dynamicanimation

emoji emoji2 enterprise exifinterface 

fragment

games glance gridlayout health heifwriter hilt

interpolator

jetifier

leanback legacy lifecycle loader localbroadcastmanager

media media2 media3 mediarouter multidex metrics

navigation

paging palette percentlayout preference print profileinstaller

recylerview remotecallback resourceinspection room

savestate security sharetarget slice slidingpanelayout startup sqlite swiperefreshlayout

test textclassifier

tracing transition tvprovider 

vectordrawable viewpager viewpager2 wear wear.compose wear.tiles wear.watchface webkit window work

material Design

数据绑定(Data Binding)

Lifecycles(关于 activity 以及 fragment 的生命周期)

LiveData(用于更新界面的数据,跟大家之前理解的 model 不一样,它可以感应生命周期)

Navigation(关于 APP 内的导航跳转)

Paging(可以理解为分页加载)

Room(原来有很多第三方的数据库 ormlite 之类的,现在 Google 出手了,这是对 sqlite 数据库的进一步封装)

ViewModel(前面说了 LiveData,而 ViewModel 就是用来管理 LiveData 的,用于连接 view 视图层和 LiveData 数据层,更重要的是它可以感应声明周期)

WorkManager(用于管理后台任务)。

2.Activity

2.1 生命周期:

onCreate

OnStart

onResume

onPause

onStop:

                        应用应释放或调整在应用对用户不可见时的无用资源。

                        例如,应用可以暂停动画效果,或从精确位置更新切换到粗略位置更新。执行 CPU 相对密集的关闭操作

onDestory:应释放先前的回调(例如 onStop())尚未释放的所有资源。

onSaveInstanceState:保存有关 Activity 视图层次结构状态的瞬时信息,例如 EditText 微件中的文本或 ListView 微件的滚动位置。--onCreate中恢复

2.2 Activity的任务栈

使用清单文件

launchMode :standard singleTop singleTask singleInstance

FLAG_ACTIVITY_NEW_TASK(singleTask)

FLAG_ACTIVITY_SINGLE_TOP(singleTop)

FLAG_ACTIVITY_CLEAR_TOP:会销毁位于它之上的所有其他 Activity,并通过 onNewIntent() 将此 intent 传送给它的已恢复实例

taskAffinity:同一应用中的所有 Activity 彼此具有亲和性

FLAG_ACTIVITY_NEW_TASK allowTaskReparenting起作用

2.3 清除返回堆栈

alwaysRetainTaskState(根Activity设置-不会清除)

clearTaskOnLaunch(根Activity设置-会清除)

finishOnTaskLaunch(单个Activity-会清楚,包括根)

  1. public class CameraComponent implements LifecycleObserver {
  2. ...
  3. @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
  4. public void initializeCamera() {
  5. if (camera == null) {
  6. getCamera();
  7. }
  8. }
  9. }

3.Fragment

3.1 带参数创建fragment

  1. getSupportFragmentManager().beginTransaction()
  2. .setReorderingAllowed(true)
  3. .add(R.id.fragment_container_view, ExampleFragment.class, bundle)
  4. .commit();
  5. --对应
  6. @Override
  7. public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
  8. int someInt = requireArguments().getInt("some_int");
  9. ...
  10. }

3.2 FragmentManager

Activity访问:

管理 Fragment 子级的 FragmentManager 的引用 getChildFragmentManager() 

访问其宿主 FragmentManager,可以使用 getParentFragmentManager()。

3.3 任务栈

addToBackStack--popBackStack

如果您在执行移除 Fragment 的事务时未调用 addToBackStack(),则提交事务时会销毁已移除的 Fragment,用户无法返回到该 Fragment。

如果您在移除某个 Fragment 时调用了 addToBackStack(),则该 Fragment 只会 STOPPED,稍后当用户返回时它会 RESUMED

saveBackStack()保存 和 restoreBackStack()弹出

3.4FragmentFactory

FragmentFactory的作用很简单:就是帮助开发者自定义并使用带参数的Fragment构造器。这对于dagger、koin等某些DI框架的使用场景中会非常有帮助

通过注解的方式来管理整个应用中的自定义的Fragment

  1. 自定义FragmentFactory
  2. public class MyFragmentFactory extends FragmentFactory {
  3. private DessertsRepository repository;
  4. public MyFragmentFactory(DessertsRepository repository) {
  5. super();
  6. this.repository = repository;
  7. }
  8. @NonNull
  9. @Override
  10. public Fragment instantiate(@NonNull ClassLoader classLoader, @NonNull String className) {
  11. Class<? extends Fragment> fragmentClass = loadFragmentClass(classLoader, className);
  12. if (fragmentClass == DessertsFragment.class) {
  13. return new DessertsFragment(repository);//这边newFragment
  14. } else {
  15. return super.instantiate(classLoader, className);
  16. }
  17. }
  18. }
  19. getSupportFragmentManager().setFragmentFactory(new MyFragmentFactory(repository));
  20. 1.注解指定fragment
  21. @TargetFragmentTag("fragment1")
  22. 2.使用
  23. mFactory=FragmentFactory.getInstance().init(this, R.id.mContentFl);
  24. mFactory.showFragment(FragmentTag.FRAGMENT1)

3.5动画

setCustomAnimations

3.6Fragment状态

3.7Fragment通信

类型

        Activity之间的通信

        Fragment之间的通信

        与子Fragment之间的通信

方法:

         使用ViewModel共享数据

        使用接口共享数据

Fragment自己的toolbar

  1. onCreate-- setHasOptionsMenu(true);
  2. onCreateOptionsMenu -- inflater.inflate(R.menu.sample_menu, menu);
  3. onOptionsItemSelected--点击事件
  4. onPrepareOptionsMenu--修改菜单
  5. requireActivity().invalidateOptionsMenu()---更新菜单
  6. xml中使用
  7. <androidx.appcompat.widget.Toolbar
  8. android:id="@+id/myToolbar"
  9. ... />
  10. java中
  11. onViewCreated--viewBinding.myToolbar.inflateMenu
  12. viewBinding.myToolbar.setOnMenuItemClickListener--点击事件
  13. viewBinding.myToolbar.setNavigationIcon(R.drawable.ic_back)--返回
  14. viewBinding.myToolbar.setNavigationOnClickListener

3.8   DialogFragment

         onCreateDialog()onDismiss() onCancel()

3.9 调试fragment

adb shell setprop log.tag.FragmentManager DEBUG
  1. 代码捕获:
  2. addOnContextAvailableListener((context) -> {
  3. if(context.getResources().getBoolean(R.bool.enable_strict_mode)) {
  4. getSupportFragmentManager().setStrictModePolicy(
  5. new FragmentStrictMode.Policy.Builder()
  6. .penaltyDeath()
  7. .detectFragmentReuse()
  8. .allowViolation(FirstFragment.class, FragmentReuseViolation.class)
  9. .build()
  10. );
  11. }
  12. }

4.lifeCycle

4.1 android观察者模式

4.2 lifeCycle主要类

LifecycleOwner:生命周期的拥有者,一般是Activity和Fragment实现这个接口,只有一个方法getLifecycle():Lifecycle
Lifecycle:表示一个生命周期过程对象,可以添加生命周期观察者
Lifecycle.State:生命周期枚举,有DESTROYED、INITIALIZED、CREATED、STARTED、RESUMED
LifecycleRegistry:Lifecycle的子类,对Lifecycle中的抽象方法进行了实现
LifecycleObserver:生命周期观察者,虽是个空接口,但可以通过Lifecycle的注解定义所有的生命周期方法
Lifecycle.Event:生命周期事件,和Activity/Fragment的相应生命周期回调一一对应,有ON_CREATE、ON_START、ON_RESUME、ON_PAUSE、ON_STOP、ON_DESTROY、ON_ANY七种取值,一般和OnLifecycleEvent注解一起使用,用来在LifecycleObserver中标注方法属于哪个生命周期

lifecycle(LifecycleRegistry)相当于被观察者,可以注册,移除通知观察者DefaultLifecycleObserver

  1. -----------------------DefaultLifecycleObserver
  2. class MyLocationListener implements DefaultLifecycleObserver {
  3. private boolean enabled = false;
  4. public MyLocationListener(Context context, Lifecycle lifecycle, Callback callback) {
  5. ...
  6. }
  7. @Override
  8. public void onStart(LifecycleOwner owner) {//LifecycleOwner
  9. if (enabled) {
  10. // connect
  11. }
  12. }
  13. public void enable() {
  14. enabled = true;
  15. if (lifecycle.getCurrentState().isAtLeast(STARTED)) {
  16. // connect if not connected
  17. }
  18. }
  19. @Override
  20. public void onStop(LifecycleOwner owner) {//LifecycleOwner
  21. // disconnect if connected
  22. }
  23. }
  24. ------------------------Activity
  25. class MyActivity extends AppCompatActivity {
  26. private MyLocationListener myLocationListener;
  27. public void onCreate(...) {
  28. myLocationListener = new MyLocationListener(this, getLifecycle(), location -> {
  29. // update UI
  30. });
  31. Util.checkUserStatus(result -> {
  32. if (result) {
  33. myLocationListener.enable();
  34. }
  35. });
  36. }
  37. }
  38. ---------------------------自定义LifecycleOwner
  39. 1、实现LifecycleOwner 接口的方法:getLifecycle()
  40. 2、注册Lifecycle new LifecycleRegistry(this)
  41. 3、在Activity生命周期函数中分发事件
  42. public class MyActivity extends Activity implements LifecycleOwner {//
  43. private LifecycleRegistry lifecycleRegistry;
  44. @Override
  45. protected void onCreate(Bundle savedInstanceState) {
  46. super.onCreate(savedInstanceState);
  47. //初始化lifecycleRegistry
  48. lifecycleRegistry = new LifecycleRegistry(this);
  49. lifecycleRegistry.markState(Lifecycle.State.CREATED);
  50. }
  51. @Override
  52. public void onStart() {
  53. super.onStart();
  54. lifecycleRegistry.markState(Lifecycle.State.STARTED);
  55. }
  56. @NonNull
  57. @Override
  58. public Lifecycle getLifecycle() {
  59. return lifecycleRegistry;
  60. }
  61. }

5.ViewModel

1.数据绑定

以上布局文件名为 activity_main.xml,因此生成的对应类为 ActivityMainBinding

android:paddingLeft-----@BindingAdapter("android:paddingLeft")

可观察的字段

* ObservableBoolean* ObservableByte* ObservableChar* ObservableShort

* ObservableInt* ObservableLong* ObservableFloat* ObservableDouble

* ObservableParcelable

可观察的集合

ObservableArrayMap ObservableArrayList

可观察的对象

BaseObservable

将布局绑定在构架组件

  1. -------------------- activity(ViewModel
  2. class ViewModelActivity extends AppCompatActivity {
  3. @Override
  4. protected void onCreate(Bundle savedInstanceState) {
  5. UserBinding binding = DataBindingUtil.setContentView(this, R.layout.user);
  6. //把viewModel设置到databinding上
  7. UserModel userModel = new ViewModelProvider(this).get(UserModel.class);
  8. binding.viewmodel = userModel;
  9. }
  10. }
  11. ---------------------ViewModel1
  12. class ScheduleViewModel extends ViewModel {
  13. LiveData username;
  14. public ScheduleViewModel() {
  15. String result = Repository.userName;
  16. userName = Transformations.map(result, result -> result.value);
  17. }
  18. }
  19. ---------------------ViewModel2--Observable
  20. class ObservableViewModel extends ViewModel implements Observable {
  21. private PropertyChangeRegistry callbacks = new PropertyChangeRegistry();
  22. @Override
  23. protected void addOnPropertyChangedCallback(
  24. Observable.OnPropertyChangedCallback callback) {
  25. callbacks.add(callback);
  26. }
  27. @Override
  28. protected void removeOnPropertyChangedCallback(
  29. Observable.OnPropertyChangedCallback callback) {
  30. callbacks.remove(callback);
  31. }
  32. void notifyChange() {
  33. callbacks.notifyCallbacks(this, 0, null);
  34. }
  35. void notifyPropertyChanged(int fieldId) {
  36. callbacks.notifyCallbacks(this, fieldId, null);
  37. }
  38. }
  39. ---------------------xml
  40. <CheckBox
  41. android:id="@+id/rememberMeCheckBox"
  42. android:checked="@{viewmodel.rememberMe}"
  43. android:onCheckedChanged="@{() -> viewmodel.rememberMeChanged()}" />
  44. ----------------------双向数据绑定@=
  45. <CheckBox
  46. android:id="@+id/rememberMeCheckBox"
  47. android:checked="@={viewmodel.rememberMe}"
  48. />
  49. -----------------实体类
  50. @InverseBindingAdapter("time")
  51. public static Time getTime(MyView view) {
  52. return view.getTime();
  53. }

2.MVVM的概念

View发生改变时,ViewModel会通知Model进行更新数据

Model数据更新后,ViewModel会通知View更新显示

谷歌发布MVVM支持DataBinding:能将数据绑定到xml中

现在谷歌又推出ViewModel和LiveData组件更方便实现MVVM

MVC MVP MVVM的区别

MVC:缺点 Activity 责任过重,Activity充当了V和C,TextView.setTextView()这种逻辑应该放在view

V(SetText)C (Activity中获取数据并显示V上)M(数据)

MVP:MVP把Activity作为view,View并不直接去请求Model,由P去请求

V/A(Activity中通过回调显示V上)P(获取数据)M(数据)

MVVM:省略了findViewbyId,setText的过程

V(xml activity) VM (实体类)M   省略了

6.LiveData

6.1优势

  • UI和实时数据保持一致

因为LiveData采用的是观察者模式,这样一来就可以在数据发生改变时获得通知,更新UI。

  • 不会发生内存泄露

观察者被绑定到组件的生命周期上,当被绑定的组件销毁(onDestroy)时,观察者会立刻自动清理自身的数据。

  • 不会再产生由于Activity处于stop状态而引起的崩溃

例如:当Activity处于后台状态时,是不会收到LiveData的任何事件的。

  • 不需要再解决生命周期带来的问题

LiveData可以感知被绑定的组件的生命周期,只有在活跃状态才会通知数据变化。

  • 实时数据刷新

当组件处于活跃状态或者从不活跃状态到活跃状态时总是能收到最新的数据

  • 解决Configuration Change问题

在屏幕发生旋转或者被回收再次启动,立刻就能收到最新的数据。

  • 数据共享

如果对应的LiveData是单例的话,就能在app的组件间分享数据。这部分详细的信息可以参考继承LiveData

  1. //----------------------创建LiveData
  2. public class NameViewModel extends ViewModel {
  3. private MutableLiveData<String> currentName;
  4. public MutableLiveData<String> getCurrentName() {
  5. if (currentName == null) {
  6. currentName = new MutableLiveData<String>();
  7. }
  8. return currentName;
  9. }
  10. }
  11. //---------------------观察LiveData(UI发生改变的时候通知)
  12. public class NameActivity extends AppCompatActivity {
  13. private NameViewModel model;
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. model = new ViewModelProvider(this).get(NameViewModel.class);
  18. final Observer<String> nameObserver = new Observer<String>() {
  19. @Override
  20. public void onChanged(@Nullable final String newName) {
  21. nameTextView.setText(newName);
  22. }
  23. };
  24. //观察Livedata
  25. model.getCurrentName().observe(this, nameObserver);
  26. }
  27. }
  28. //---------------------更新LiveData,(更新UI)
  29. button.setOnClickListener(new OnClickListener() {
  30. @Override
  31. public void onClick(View v) {
  32. String anotherName = "John Doe";
  33. model.getCurrentName().setValue(anotherName);
  34. }
  35. });
  36. //LiveData转换
  37. Transformations.map()
  38. Transformations.switchMap()

 6.2数据状态

​​​​​​​

  1. class SearchManager implements SavedStateRegistry.SavedStateProvider {
  2. private static String PROVIDER = "search_manager";
  3. private static String QUERY = "query";
  4. private String query = null;
  5. public SearchManager(SavedStateRegistryOwner registryOwner) {
  6. registryOwner.getLifecycle().addObserver((LifecycleEventObserver) (source, event) -> {
  7. if (event == Lifecycle.Event.ON_CREATE) {
  8. SavedStateRegistry registry = registryOwner.getSavedStateRegistry();
  9. // Register this object for future calls to saveState()
  10. registry.registerSavedStateProvider(PROVIDER, this);
  11. // Get the previously saved state and restore it
  12. Bundle state = registry.consumeRestoredStateForKey(PROVIDER);
  13. // Apply the previously saved state
  14. if (state != null) {
  15. query = state.getString(QUERY);
  16. }
  17. }
  18. });
  19. }
  20. @NonNull
  21. @Override
  22. public Bundle saveState() {
  23. Bundle bundle = new Bundle();
  24. bundle.putString(QUERY, query);
  25. return bundle;
  26. }
  27. ...
  28. }
  29. class SearchFragment extends Fragment {
  30. private SearchManager searchManager = new SearchManager(this);
  31. ...
  32. }

7.Work

原理:用来执行后台任务的

优点:

  • 版本兼容性强,向后兼容至API 14。
  • 可以指定约束条件,比如可以选择必须在有网络的条件下执行。
  • 可定时执行也可单次执行。
  • 监听和管理任务状态。
  • 多个任务可使用任务链。
  • 保证任务执行,如当前执行条件不满足或者App进程被杀死,它会等到下次条件满足或者App进程打开后执行。
  • 支持省电模式。

替换:

WorkManager API 是一个适合用来替换先前的 Android 后台调度 API(包括 FirebaseJobDispatcherGcmNetworkManager  和 JobScheduler)的推荐组件。

应用:

  • 向后端服务发送日志或分析数据。
  • 定期将应用数据与服务器同步。

AS中引用build.gradle

  1. dependencies {
  2. def work_version = "2.7.1"
  3. // (Java only)
  4. implementation "androidx.work:work-runtime:$work_version"
  5. // Kotlin + coroutines
  6. implementation "androidx.work:work-runtime-ktx:$work_version"
  7. // optional - RxJava2 support
  8. implementation "androidx.work:work-rxjava2:$work_version"
  9. // optional - GCMNetworkManager support
  10. implementation "androidx.work:work-gcm:$work_version"
  11. // optional - Test helpers
  12. androidTestImplementation "androidx.work:work-testing:$work_version"
  13. // optional - Multiprocess support
  14. implementation "androidx.work:work-multiprocess:$work_version"
  15. }

WorkManager 可处理三种类型的永久性工作:

  • 立即执行:必须立即开始且很快就完成的任务,可以加急。
  • 长时间运行:运行时间可能较长(有可能超过 10 分钟)的任务。
  • 可延期执行:延期开始并且可以定期运行的预定任务。
类型周期使用方式
立即一次性OneTimeWorkRequest 和 Worker

如需处理加急工作- 调用 setExpedited()

长期运行一次性或定期

任意 WorkRequest 或 Worker

在工作器中调用 setForeground() 来处理通知

可延期一次性或定期PeriodicWorkRequest 和 Worker

基础使用:

1.定义worker ,实现dowork

public class UploadWorker extends Worker {

2.利用建造者创建workRequest

  1. WorkRequest uploadWorkRequest =
  2. new OneTimeWorkRequest.Builder(UploadWorker.class)
  3. .build();

3.将 WorkRequest 提交给系统

  1. WorkManager
  2. .getInstance(myContext)
  3. .enqueue(uploadWorkRequest);

具体用法:

常见的Worker

1.自动运行在后台线程的Worker

2.结合协程的CoroutineWorker

​​​​​​​3.结合RxJava2RxWorker和以上三个类的基类的ListenableWorker

4.RemoteListenableWorker和RemoteCoroutineWorker

从 WorkManager 2.6 开始,借助 RemoteListenableWorker 或者 RemoteCoroutineWorker可以将任务运行在任意指定进程,实现跨进程的监听

  1. //------------------------work用法(中间进度)
  2. public class ProgressWorker extends Worker {
  3. private static final String PROGRESS = "PROGRESS";
  4. private static final long DELAY = 1000L;
  5. public ProgressWorker(
  6. @NonNull Context context,
  7. @NonNull WorkerParameters parameters) {
  8. super(context, parameters);
  9. // Set initial progress to 0
  10. setProgressAsync(new Data.Builder().putInt(PROGRESS, 0).build());
  11. }
  12. @NonNull
  13. @Override
  14. public Result doWork() {
  15. try {
  16. Thread.sleep(DELAY);
  17. } catch (InterruptedException exception) {
  18. }
  19. // Set progress to 100 after you are done doing your work.
  20. setProgressAsync(new Data.Builder().putInt(PROGRESS, 100).build());
  21. return Result.success();
  22. }
  23. }

创建workRequest

    1. //--------------------一次性任务
    2. WorkRequest myWorkRequest = OneTimeWorkRequest.from(MyWork.class);
    3. //-----------------------加急任务
    4. OneTimeWorkRequest request = new OneTimeWorkRequestBuilder<T>()
    5. .setInputData(inputData)
    6. .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
    7. //加急工作
    8. .build();
    9. //-----------------------延迟任务
    10. WorkRequest myWorkRequest =
    11. new OneTimeWorkRequest.Builder(MyWork.class)
    12. .setInitialDelay(10, TimeUnit.MINUTES)
    13. .build();
    14. -------------------------重试任务
    15. WorkRequest myWorkRequest =
    16. new OneTimeWorkRequest.Builder(MyWork.class)
    17. .setBackoffCriteria(
    18. BackoffPolicy.LINEAR,//重试间隔都会增加约 10
    19. OneTimeWorkRequest.MIN_BACKOFF_MILLIS,//此值不能超过 10
    20. TimeUnit.MILLISECONDS)
    21. .build();
    22. // ------------------------构建约束条件
    23. 约束条件(NetworkType BatteryNotLow RequiresCharging DeviceIdle StorageNotLow)
    24. val constraints = Constraints.Builder()
    25. .setRequiresBatteryNotLow(true) // 非电池低电量
    26. .setRequiredNetworkType(NetworkType.CONNECTED) // 网络连接的情况
    27. .setRequiresStorageNotLow(true) // 存储空间足
    28. .build()
    29. // 储存照片
    30. val save = OneTimeWorkRequestBuilder<SaveImageToFileWorker>()
    31. .setConstraints(constraints)
    32. .addTag(TAG_OUTPUT)
    33. .build()
    34. continuation = continuation.then(save)
    35. //-------------------------标记---tag
    36. WorkRequest myWorkRequest =
    37. new OneTimeWorkRequest.Builder(MyWork.class)
    38. .addTag("cleanup")
    39. .build();
    40. //-----------------------data
    41. WorkRequest myUploadWork =
    42. new OneTimeWorkRequest.Builder(UploadWork.class)
    43. .setInputData(
    44. new Data.Builder()
    45. .putString("IMAGE_URI", "http://...")
    46. .build()
    47. )
    48. .build();
    49. //-------协程--getForegroundInfo可让 WorkManager 在您调用 setExpedited() 时显示通知。
    50. class ExpeditedWorker(appContext: Context, workerParams: WorkerParameters):
    51. CoroutineWorker(appContext, workerParams) {
    52. override suspend fun getForegroundInfo(): ForegroundInfo {
    53. return ForegroundInfo(
    54. NOTIFICATION_ID, createNotification()
    55. )
    56. }
    57. override suspend fun doWork(): Result {
    58. TODO()
    59. }
    60. private fun createNotification() : Notification {
    61. TODO()
    62. }
    63. }
    64. //----------------------定期任务
    65. PeriodicWorkRequest saveRequest =
    66. new PeriodicWorkRequest.Builder(SaveImageToFileWorker.class, 1, TimeUnit.HOURS)
    67. // Constraints
    68. .build();
    69. //-----------------------定时任务,每小时的15分钟执行的任务
    70. WorkRequest saveRequest =
    71. new PeriodicWorkRequest.Builder(SaveImageToFileWorker.class,
    72. 1, TimeUnit.HOURS,
    73. 15, TimeUnit.MINUTES)
    74. .build();

WorkManager使用

  1. //---------------------多任务执行(连接)
  2. workManager.beginWith(
  3. mutableListOf(
  4. OneTimeWorkRequest.from(CleanUpWorker::class.java)
  5. ))
  6. .then(OneTimeWorkRequestBuilder<BlurWorker>().setInputData(createInputDataForUri()).build())
  7. .then(OneTimeWorkRequestBuilder<SaveImageToFileWorker>().build())
  8. .enqueue()
  9. // -----------------------多任务按顺序执行
  10. workManager.beginUniqueWork(//beginUniqueWork
  11. IMAGE_MANIPULATION_WORK_NAME, // 任务名称
  12. ExistingWorkPolicy.REPLACE, // 任务相同的执行策略 分为REPLACE,KEEP,APPEND
  13. mutableListOf(
  14. OneTimeWorkRequest.from(CleanUpWorker::class.java)
  15. ))
  16. .then(OneTimeWorkRequestBuilder<BlurWorker>().setInputData(createInputDataForUri()).build())
  17. .then(OneTimeWorkRequestBuilder<SaveImageToFileWorker>().build())
  18. .enqueue()
  19. //-------------------------唯一工作执行
  20. PeriodicWorkRequest sendLogsWorkRequest = new
  21. PeriodicWorkRequest.Builder(SendLogsWorker.class, 24, TimeUnit.HOURS)
  22. .setConstraints(new Constraints.Builder()
  23. .setRequiresCharging(true)
  24. .build()
  25. )
  26. .build();
  27. WorkManager.getInstance(this).enqueueUniquePeriodicWork(//唯一
  28. "sendLogs",
  29. ExistingPeriodicWorkPolicy.KEEP,
  30. sendLogsWorkRequest);
  31. //---------------------合并器,父输出传入子输入
  32. OneTimeWorkRequest cache = new OneTimeWorkRequest.Builder(PlantWorker.class)
  33. .setInputMerger(ArrayCreatingInputMerger.class)
  34. .setConstraints(constraints)
  35. .build();
  36. //----------------------------取消任务
  37. // by id
  38. workManager.cancelWorkById(syncWorker.id);
  39. // by name
  40. workManager.cancelUniqueWork("sync");
  41. // by tag
  42. workManager.cancelAllWorkByTag("syncTag");
  43. //--------------------------复杂工作查询Workquery,从上面tag中查找,检测状态
  44. workManager.getWorkInfoByIdLiveData(syncWorker.id)
  45. .observe(getViewLifecycleOwner(), workInfo -> {
  46. if (workInfo.getState() != null &&
  47. workInfo.getState() == WorkInfo.State.SUCCEEDED) {
  48. Snackbar.make(requireView(),
  49. R.string.work_completed, Snackbar.LENGTH_SHORT)
  50. .show();
  51. }
  52. });
  53. WorkQuery workQuery = WorkQuery.Builder
  54. .fromTags(Arrays.asList("syncTag"))
  55. .addStates(Arrays.asList(WorkInfo.State.FAILED, WorkInfo.State.CANCELLED))
  56. .addUniqueWorkNames(Arrays.asList("preProcess", "sync")
  57. )
  58. .build();
  59. ListenableFuture<List<WorkInfo>> workInfos = workManager.getWorkInfos(workQuery);
  60. //--------------------------------观察进度
  61. WorkManager.getInstance(getApplicationContext())
  62. // requestId is the WorkRequest id
  63. .getWorkInfoByIdLiveData(requestId)
  64. .observe(lifecycleOwner, new Observer<WorkInfo>() {
  65. @Override
  66. public void onChanged(@Nullable WorkInfo workInfo) {
  67. if (workInfo != null) {
  68. Data progress = workInfo.getProgress();
  69. int value = progress.getInt(PROGRESS, 0)
  70. // Do something with progress
  71. }
  72. }
  73. });

调试:

public class MyApplication extends Application implements Configuration.Provider {
    @NonNull
    @Override
    public Configuration getWorkManagerConfiguration() {
        return new Configuration.Builder()
                .setMinimumLoggingLevel(android.util.Log.DEBUG)
                .build();
    }
}

adb shell dumpsys jobscheduler

adb shell am broadcast -a "androidx.work.diagnostics.REQUEST_DIAGNOSTICS" -p "<your_app_package_name>"
 

协程:

  • 处理多任务并发的手段,最大的特点就是可以自动帮助我们切换线程​​​​​​​
  • 协程就像轻量级的线程。线程由系统调度,协程由开发者控制。
  • kotlin协程本质上是对线程池的封装
  1. GlobalScope.launch {
  2. withContext(Dispatchers.Main){
  3. //切换线程
  4. }
  5. }
  6. //主线程协程
  7. GlobalScope.launch(Dispatchers.Main) {}
  8. lifecycleScope.launch {}
  9. viewModelScope.launch {}
  10. //默认情况下协程是串行的
  11. //并行方式
  12. lifecycleScope.launch {
  13. lifecycleScope.async { getDataA() }
  14. lifecycleScope.async { getDataB() }
  15. }
  16. //协程停止
  17. ?.cancel()
  18. lifecycleScope和viewModelScope会绑定调用者的生命周期,因此通常情况下不需要手动去停止

添加依赖:

implementation'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.0'

implementation'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.0'

​​​​​​​​​​​​​​8.Room

8.1示例

  1. ------------------------Entity-----------------------------
  2. @Entity
  3. public class User {
  4. @PrimaryKey
  5. public int uid;
  6. @ColumnInfo(name = "first_name")
  7. public String firstName;
  8. @ColumnInfo(name = "last_name")
  9. public String lastName;
  10. }
  11. ------------------------Dao-----------------------------
  12. @Dao
  13. public interface UserDao {
  14. @Query("SELECT * FROM user")
  15. List<User> getAll();
  16. @Query("SELECT * FROM user WHERE uid IN (:userIds)")
  17. List<User> loadAllByIds(int[] userIds);
  18. @Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
  19. "last_name LIKE :last LIMIT 1")
  20. User findByName(String first, String last);
  21. @Insert
  22. void insertAll(User... users);
  23. @Delete
  24. void delete(User user);
  25. }
  26. ------------------------Database-----------------------------
  27. @Database(entities = {User.class}, version = 1)
  28. public abstract class AppDatabase extends RoomDatabase {
  29. public abstract UserDao userDao();
  30. }
  31. AppDatabase db = Room.databaseBuilder(getApplicationContext(),
  32. AppDatabase.class, "database-name").build();
  33. UserDao userDao = db.userDao();
  34. List<User> users = userDao.getAll();

8.2

​​​​​​​
javaCompileOptions {
    annotationProcessorOptions {
        arguments = ["room.schemaLocation":
                             "$projectDir/schemas".toString()]
    }
}

配置如上可以看到json文件

8.3 调试数据库

adb shell
sqlite3 /data/data/your-app-package/databases/XXX.db

.help 帮助

.exit  退出

.table 查看表

select * from  "具体表名"; 注意分隔 查询所有字段

排序 order by:

select * from  "具体表名" order by XXX;排序

select * from  "具体表名" order by XXX desc;逆序

条件查询 where:

select * from "表名" where "字段名"='字段值';

select * from "表名" where "字段名" between "" and  "";

select * from "表名" where "字段名" not between "" and  "";

select * from "表名" where "字段名" is NULL;空查询

多条件查询 or ,and,in, not in:

select * from "表名" where "字段条件语句1"  and "字段条件语句2" or "字段条件语句3";

select * from "表名" where "字段名" in "字段值1,字段值2" ;

select * from "表名" where "字段名" not  in "字段值1,字段值2" ;

模糊查询 like:

select * from "表名" where "字段名"  like "字段值";

通配符:_ 代表一个未指定字符,% 代表不定个未指定字符

select * from "表名" where "字段名"  like " _";以_表示未知字符

select * from "表名" where "字段名" like '[ALN]%'以A或L或N开头的

更新:

update ‘表名’ set value='字段值' where ‘字段名’='字段值';

多表查询:

select "表别名.字段名" from "表名A" A left join "表名B" B ON A.Key = B.key

select "字段名" from "表名A" A left join "表名B" B ON A.Key = B.key Where B.key is null

select "字段名" from "表名A" A inner join "表名B" B ON A.Key = B.key

select "字段名" from "表名A" A right join "表名B" B ON A.Key = B.key

select "字段名" from "表名A" A right join "表名B" B ON A.Key = B.key Where A.key is null

​​​​​​​select "字段名" from "表名A" A full outer join "表名B" B ON A.Key = B.key

​​​​​​​select "字段名" from "表名A" A full outer join "表名B" B ON A.Key = B.key Where A.key is null or B.key is null

​​​​​​​​​​​​​​

 

参考:即学即用Android Jetpack - WorkManger - 简书

LiveData 概览  |  Android 开发者  |  Android Developers

https://blog.csdn.net/m0_37700275/article/details/104683011

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号