当前位置:网站首页>Impressions of Embrace Jetpack
Impressions of Embrace Jetpack
2022-08-02 15:10:00 【Who covereth the heaven is difficult】
目录
前言
Before the text begins, I have to say a few words,Can ignore this section,哈哈...问个问题:you have embracedJetpack了吗?今天我们就来学习一下Jetpack组件库,No technical explanation today,We just briefly understand what isJetpack,So today's content is easy,You can spend these few minutes happily.!
本文参考资料:慕课网《移动端架构师》课程学习
官网地址:https://developer.android.google.cn/jetpack
一、什么是Jetpack
Jetpackis a collection of many excellent components,Is Google introduced a set of specification for developers gradually unified development of the new architecture.
Google's officialJetpack的介绍如下:
Jetpack 是一个由多个库组成的套件,可帮助开发者遵循最佳做法、减少样板代码并编写可在各种 Android 版本和设备中一致运行的代码,让开发者可将精力集中于真正重要的编码工作.
We need to master is importantAndroid Architecture Components,简称AAC,即:安卓架构组件,We can get a general understanding of it through the following picture:
二、Jetpack的优势
- JetpackNumerous components are provided with lifecycle-aware capabilities,可以减少NPE崩溃、Memory leaks and template code,Allows us to develop more robust and high-quality applications.
- JetpackProvide components can be used alone,也可以搭配使用,并且搭配KotlinLanguage features can further accelerate development.
三、Jetpack组件库介绍
The following is a brief introduction of our usual several components is often used in the development of library:
3.1、Navigation
it is for singleActivityIntra-end routing by architecture
- 特点:Activity、Fragment、DialogComponents that provide routing capabilities、Portable navigation parameters、Specify a transition animation、支持deeplinedirect page、fragmentBack up the stack management ability;
- 缺点:十分依赖xml文件(Build the page navigation structure),不利于模块化,组件化开发.
The way to add dependencies is as follows:
implementation "androidx.navigation:navigation-fragment:versionNumber"
implementation "androidx.navigation:navigation-ui:versionNumber"
路由跳转,可以携带参数,Specify a transition animation:
NavController navController;
navController.navigate(int resId,Bundle args,NavOptions navOptions);
deepLinkRealize the ability to reach the page directly:
navController.handleDeepLink(intent);
管理Fragment回退栈:
navController.popBackStack(int destinationId,boolean inclusive);
3.2、Lifecycle
It is a component with host lifecycle awareness
特点:持有组件(比如:Activity或者Fragment)生命周期状态的信息,并且允许其他对象观察此状态.
The way to add dependencies is as follows:
implementation 'androidx.appcompat:appcompat:1.3.0'
// Or introduce the following dependencies separately
implementation "androidx.lifecycle:lifecycle-common:2.5.0"
经典用法:
// Fragment中实现了Lifecycle
public class Fragment implement xxx,LifecycleOwner{
//Inside the object iskey-value的map集合,Used to store registered inObserver对象
//会在FragmentThe traverse stored in each life cycle methodObserver观察者,So as to achieve the distribution host state
LifecycleRegistry mLifecycleRegistry;
@Override
@NonNull
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
private void initLifecycle() {
mLifecycleRegistry = new LifecycleRegistry(this);
}
}
// 使用方式:Any class implementationLifecycleObserver接口,Add the following annotation to the lifecycle method
class MyLocation implements LifecycleObserver{
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreate(@NonNull LifecycleOwner owner) {}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
void onDestroy(@NonNull LifecycleOwner owner){}
}
// Then subscribe on the host page
getLifecycle().addObserver(myLocation); //注册观察者,Observe Host Lifecycle Status
3.3、ViewModel
It is a data storage component lifecycle perception
特点:Data is not lost when page configuration is changed、生命周期感知、数据共享
The way to add dependencies is as follows:
implementation 'androidx.appcompat:appcompat:1.3.0'
// Or separately introduce the following components,通常情况下ViewModel会和LiveData搭配使用
implementation "androidx.lifecycle:lifecycle-viewmodel:2.5.0"
implementation "androidx.lifecycle:lifecycle-livedata:2.5.0"
ViewModel的数据存储、生命周期感知:
// 创建ViewModel类,Change does not perceive the host all life cycle,senses the hostonDestroyBe destroyed when the state changes
class MyViewModel extends ViewModel {
@Override
protected void onCleared() {
super.onCleared();
// The host is destroyed,会执行到这里,Release resources to clean up
}
MutableLiveData<User> userInfoData = new MutableLiveData<>();
public void getUserInfo(LifecycleOwner owner, Observer<User> observer){
userInfoData.observe(owner,observer);
// ......Query user data from database
userInfoData.setValue(user);
}
}
ViewModel数据共享:场景:单Activity多Fragment
// 构建ViewModel实例对象,需要使用ViewModelProvider来获取ViewModel对象
// 如果ViewModelStoreThen return to public instance has existed,如果不存在,则使用factory创建并缓存
// 不同fragmentget the sameViewModel实例,从而实现数据共享
class FragmentA extends Fragment{
public void onCreate(Bundle bundle){
MyViewModel viewModel = new ViewModelProvider(getActivity().getViewModelStore(),new ViewModelProvider.NewInstanceFactory()).get(MyViewModel.class);
}
}
3.4、LiveData
It is a data subscription with lifecycle awareness、分发组件
- 特点:支持共享资源、支持黏性事件的分发(After registered observers can receive before the data)、不再需要手动处理生命周期(Automatically associated with the host lifecycle,It will automatically deregister when the host is destroyedObserver)、确保界面符合数据状态
- 缺点:Sticky events do not support cancellation
MutableLiveData<T> liveData = new MutableLiveData<>();
// Register an observer bound to the host lifecycle,Host destruction will automatically cancel the registration
observe(LifecycleOwner owner, Observer<? super T> observer)
// Host life cycle not observed,Does not automatically deregister
observeForever(Observer<? super T> observer)
// The following two methods are to distribute data to all observers
// 只能用在主线程
setValue(T value)
// 子线程,Main thread can use
postValue(T value)
3.5、Room
它是轻量级orm数据库,本质上是一个SQLite抽象层
特点:使用更加简单(类似于Retrofit库),通过注解的方式实现相关功能,Automatically generate implementation classes at compile timeimpl
The way to add dependencies is as follows:
implementation "androidx.room:room-runtime:2.4.2"
annotationProcessor "androidx.room:room-compiler:2.4.2"
Room数据库读写操作:
// Create an entity layer that manipulates the database
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll();
@Update
User updateUser(User...users);
@Insert
void insertAll(User...users);
@Delete
void deleteUser(User user);
}
// 创建数据库
@Database(entities = {User.class},version = 1)
public abstract class MyDatabase extends RoomDatabase {
public static MyDatabase myDb;
static {
myDb = Room.databaseBuilder(getApplicationContext(),
MyDatabase.class,"database-name").build();
}
public abstract UserDao userDao();
}
// Singleton object via database,获取userDao数据操作对象,访问数据库
myDb.userDao().getAll();
3.6、DataBinding
I believe many people are already familiar with it,这里就简单的说一下,It is just a tool,它解决的是View和数据之间的双向绑定,MVVM是一种架构模式,这两者是有本质区别的.
特点:数据与视图双向绑定、数据绑定空安全、减少模板代码、释放Activity/Fragment的压力
开启dataBinding:
android{
...
dataBinding{
enabled = true
}
}
Binding data in layout:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="user"
type="com.jarchie.foundation.User" />
<import type="com.jarchie.foundation.UserManager" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvName"
android:layout_width="200dp" //cannot use dynamic binding
android:layout_height="wrap_content"
android:text="@{user.name}" //One-way binding data changes automatically notifiedUI
android:text="@{[email protected]/addStr}" //String concatenation requires referencing resources
android:text="@{UserManager.getUsername()}" //调用静态方法,The class must be imported first
android:textSize="@{@dimen/16sp}" //资源引用
android:onClick="@{()->UserManager.login()}" //lambdaExpression form to implement click event
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
//Two-way binding data changes are automatically updatedUI,UIChanges can also be automatically updateduser中name的数据,One more than one-way binding=
android:text="@={user.name}"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
当我们写完了xml布局之后,每一个dataBindingThe layout will generate a file named by the layout file nameDataBinding类,比如:
ActivityMainBinding binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
binding.tvName.setText("不用写findViewById啦啦啦啦啦");
3.7、WorkManager
It is a new generation of background task management components,service能做的事情它都能做
特点:支持周期性任务调度、链式任务调度、丰富的任务约束条件(For example, the network conditions must bewifiConditions in order to perform),even if the program exits,依旧能保证任务的执行
The way to add dependencies is as follows:
implementation "androidx.work:work-runtime:2.7.1"
执行任务:
// 构建任务
public class DownloadFileWorker extends Worker{
public DownloadFileWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
return Result.success();
}
}
// build tasksRequest对象
OneTimeWorkRequest request = new OneTimeWorkRequest
.Builder(DownloadFileWorker.class)
.build();
// 把任务加入到任务队列
WorkContinuation workContinuation = WorkManager.getInstance(this).beginWith(request);
workContinuation.then(workB).then(workC).enqueue();
OK,The above components are all of the components that we may often use in our daily development.,The rest of the components will not be introduced here.,If you need it, you can search for related articles on the Internet.,Or to learn to Google's website.
今天的内容就到这里啦,下期再会!
边栏推荐
猜你喜欢
随机推荐
国内IT市场还有发展吗?有哪些创新好用的IT运维工具可以推荐?
流,向量场,和微分方程
flutter中App签名
LLVM系列第十八章:写一个简单的IR处理流程Pass
1.RecyclerView是什么
加强版Apktool堪称逆向神器
PyTorch②---transforms结构及用法
PyTorch⑩---卷积神经网络_一个小的神经网络搭建
Cannot figure out how to save this field into database. You can consider adding a type converter for
PyTorch⑤---卷积神经网络_卷积层
使用预训练语言模型进行文本生成的常用微调策略
boost库智能指针
机器学习和深度学习中的梯度下降及其类型
机器学习---监督学习、无监督学习
LLVM系列第二十一章:写一个简单的Loop Pass
基于GPT的隐变量表征解码结构
“非图灵完备”到底意味着什么
LLVM系列第二十二章:写一个简单的编译时函数调用统计器(Pass)
In the Visual studio code solutions have red wavy lines
Redis database related commands