Android Architecture Components ——LiveData使用,Android面试题整理

public MutableLiveData getLiveData() {

if (mLiveData == null) {

mLiveData = new MutableLiveData<>();

}

return mLiveData;

}

public void onNormalSetUse() {

getLiveData().setValue(“hahahhahaha===>set”);

}

public void onNormalPostUse() {

new Thread(new Runnable() {

@Override

public void run() {

getLiveData().postValue(“hahahhahaha==>post”);

}

}).start();

}

}

  • 在Activity中进行监听

import android.arch.lifecycle.MutableLiveData;

import android.arch.lifecycle.Observer;

import android.arch.lifecycle.ViewModelProviders;

import android.os.Bundle;

import android.support.annotation.Nullable;

import android.support.v7.app.AppCompatActivity;

import android.util.Log;

import android.view.View;

import cn.tsou.google2019io.R;

import cn.tsou.google2019io.livedata.viewmodel.LiveDataViewModel;

public class LiveDataActivity extends AppCompatActivity {

private LiveDataViewModel viewModel;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_live_data);

}

@Override

public void onAttachedToWindow() {

super.onAttachedToWindow();

viewModel = ViewModelProviders.of(this).get(LiveDataViewModel.class);

MutableLiveData liveData = viewModel.getLiveData();

liveData.observe(this, new Observer() {

@Override

public void onChanged(@Nullable String s) {

Log.d(“huangxiaoguo”, s);

}

});

}

public void onNormalSetUse(View view) {

viewModel.onNormalSetUse();

}

public void onNormalPostUse(View view) {

viewModel.onNormalPostUse();

}

}

记住是ViewModelProviders不是ViewModelProvider。

  • setValue与postValue的区别

setValue:

@MainThread

protected void setValue(T value) {

assertMainThread(“setValue”);

mVersion++;

mData = value;

dispatchingValue(null);

}

postValue:

protected void postValue(T value) {

boolean postTask;

synchronized (mDataLock) {

postTask = mPendingData == NOT_SET;

mPendingData = value;

}

if (!postTask) {

return;

}

ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);

}

private final Runnable mPostValueRunnable = new Runnable() {

@Override

public void run() {

Object newValue;

synchronized (mDataLock) {

newValue = mPendingData;

mPendingData = NOT_SET;

}

//noinspection unchecked

setValue((T) newValue);

}

};

发现postValue其实内部进行了线程转换,准终在调用setValue在主线程执行。

小结:setValue只能在主线程进行调用,postValue可以在子线程进行调用

在ViewModel中使用上下文

viewModel不可持有view的引用或者任何持有activity上下文的类的引用,如果需要Application的context的话可以继承AndroidViewModel。

  • viewModel

package cn.tsou.google2019io.livedata.viewmodel;

import android.app.Application;

import android.arch.lifecycle.AndroidViewModel;

import android.arch.lifecycle.MutableLiveData;

import android.support.annotation.NonNull;

import android.widget.Toast;

/**

  • A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.

  • viewModel不可持有view的引用或者任何持有activity上下文的类的引用

  • 如果需要Application的context的话可以继承AndroidViewModel

  • Activity重复创建的时候,持有的是同一个viewModel实例

*/

public class LiveDataContextViewModel extends AndroidViewModel {

public LiveDataContextViewModel(@NonNull Application application) {

super(application);

}

private MutableLiveData mLiveData;

public MutableLiveData getLiveData() {

if (mLiveData == null) {

mLiveData = new MutableLiveData<>();

}

return mLiveData;

}

public void onNormalSetUse() {

Toast.makeText(getApplication(), “如果需要Application的context的话可以继承AndroidViewModel”, Toast.LENGTH_LONG).show();

getLiveData().setValue(“hahahhahaha===>set”);

}

/**

  • 当不需要ViewModel时(比如Activity调用finish()方法),

  • ViewModel会回调onCleared()方法,之后会销毁自己。这一好处也是避免了内存泄漏的情况发生

*/

@Override

protected void onCleared() {

//处理一些操作

super.onCleared();

}

}

小结:getApplication()即是全局的上下文

  • Activity中进行数据监听

import android.arch.lifecycle.MutableLiveData;

import android.arch.lifecycle.Observer;

import android.arch.lifecycle.ViewModelProviders;

import android.support.annotation.Nullable;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import cn.tsou.google2019io.R;

import cn.tsou.google2019io.livedata.viewmodel.LiveDataContextViewModel;

import cn.tsou.google2019io.livedata.viewmodel.LiveDataViewModel;

public class LiveDataContextActivity extends AppCompatActivity {

private LiveDataContextViewModel viewModel;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_live_data_context);

}

@Override

public void onAttachedToWindow() {

super.onAttachedToWindow();

viewModel = ViewModelProviders.of(this).get(LiveDataContextViewModel.class);

MutableLiveData liveData = viewModel.getLiveData();

liveData.observe(this, new Observer() {

@Override

public void onChanged(@Nullable String s) {

Log.d(“huangxiaoguo”, s);

}

});

}

public void onNormalSetUse(View view) {

viewModel.onNormalSetUse();

}

}

ViewModel中传递参数

viewmodel传递数据一般需要自定义Factory

  • ViewModel

import android.arch.lifecycle.MutableLiveData;

import android.arch.lifecycle.ViewModel;

import android.arch.lifecycle.ViewModelProvider;

import android.util.Log;

public class LiveDataSetDataViewModel extends ViewModel {

private String mKey;

private String mKey1;

public LiveDataSetDataViewModel(String key, String key1) {

this.mKey = key;

this.mKey1 = key1;

}

public static class Factory implements ViewModelProvider.Factory {

private String mKey;

private String mKey1;

public Factory(String key, String key1) {

mKey = key;

mKey1 = key1;

}

@Override

public T create(Class modelClass) {

return (T) new LiveDataSetDataViewModel(mKey, mKey1);

}

}

private MutableLiveData mLiveData;

public MutableLiveData getLiveData() {

if (mLiveData == null) {

mLiveData = new MutableLiveData<>();

}

return mLiveData;

}

public void onNormalSetUse() {

Log.d(“huangxiaoguo”, mKey + “------” + mKey1);

getLiveData().setValue(“hahahhahaha===>set”);

}

@Override

protected void onCleared() {

super.onCleared();

}

}

  • Acticity

import android.arch.lifecycle.MutableLiveData;

import android.arch.lifecycle.Observer;

import android.arch.lifecycle.ViewModelProviders;

import android.os.Bundle;

import android.support.annotation.Nullable;

import android.support.v7.app.AppCompatActivity;

import android.util.Log;

import android.view.View;

import cn.tsou.google2019io.R;

import cn.tsou.google2019io.livedata.viewmodel.LiveDataSetDataViewModel;

public class LiveDataSetDataActivity extends AppCompatActivity {

private LiveDataSetDataViewModel viewModel;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_live_data_set_data);

}

@Override

public void onAttachedToWindow() {

super.onAttachedToWindow();

viewModel = ViewModelProviders.of(this, new LiveDataSetDataViewModel.Factory(“传递的参数”,“传递的参数1”)).get(LiveDataSetDataViewModel.class);

MutableLiveData liveData = viewModel.getLiveData();

liveData.observe(this, new Observer() {

@Override

public void onChanged(@Nullable String s) {

Log.d(“huangxiaoguo”, s);

}

});

}

public void onNormalSetUse(View view) {

viewModel.onNormalSetUse();

}

}

自定义LiveData

自定义LiveData一般都是重写onActive 和onInactive ,这里就拿一篇网上现成的例子来说明(范例来源:gdutxiaoxu的博客

这里我们以观察网络状态变化为例子讲解

首先我们自定义一个 Class NetworkLiveData,继承 LiveData,重写它的 onActive 方法和 onInactive 方法

在 onActive 方法中,我们注册监听网络变化的广播,即ConnectivityManager.CONNECTIVITY_ACTION。在 onInactive 方法的时候,我们注销广播。

public class NetworkLiveData extends LiveData {

private final Context mContext;

static NetworkLiveData mNetworkLiveData;

private NetworkReceiver mNetworkReceiver;

private final IntentFilter mIntentFilter;

private static final String TAG = “NetworkLiveData”;

public NetworkLiveData(Context context) {

mContext = context.getApplicationContext();

mNetworkReceiver = new NetworkReceiver();

mIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);

}

public static NetworkLiveData getInstance(Context context) {

if (mNetworkLiveData == null)

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享

{

mNetworkLiveData = new NetworkLiveData(context);

}

return mNetworkLiveData;

}

@Override

protected void onActive() {

super.onActive();

Log.d(TAG, “onActive:”);

mContext.registerReceiver(mNetworkReceiver, mIntentFilter);

}

@Override

protected void onInactive() {

super.onInactive();

Log.d(TAG, "onInactive: ");

mContext.unregisterReceiver(mNetworkReceiver);

}

private static class NetworkReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

ConnectivityManager manager = (ConnectivityManager) context

.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = manager.getActiveNetworkInfo();

getInstance(context).setValue(activeNetwork);

}

}

}

这样,当我们想监听网络变化的时候,我们只需要调用相应的 observe 方法即可,方便又快捷。

NetworkLiveData.getInstance(this).observe(this, new Observer() {

@Override

public void onChanged(@Nullable NetworkInfo networkInfo) {

Log.d(TAG, “onChanged: networkInfo=” +networkInfo);

}

});

小结:如果想要在数据传递之前对数据进行统一操作,重写setValue方法即可,因为postValue最终调用的还是setValue。

Fragment中使用

在fragment中livaData的使用和Activity相同

  • ViewModel

import android.arch.lifecycle.MutableLiveData;

import android.arch.lifecycle.ViewModel;

public class LiveDataFragmentViewModel extends ViewModel {

private MutableLiveData mLiveData;

public MutableLiveData getLiveData() {

if (mLiveData == null) {

mLiveData = new MutableLiveData<>();

}

return mLiveData;

}

public void onNormalSetUse() {

getLiveData().setValue(“LiveData3Fragment===>set”);

}

public void onNormalPostUse() {

new Thread(new Runnable() {

上一篇:短视频系统,折叠cell的使用


下一篇:工具栏显示提示信息