LiveData 和 LifecycleObserver 有什么区别
What is the difference between LiveData and LifecycleObserver
我已经阅读了android官方文档中关于Life Cycle and Live Data的文档。我知道 class 实现了 LifeCycleObserver 并自动关闭或打开位置侦听器。我也知道实时数据可以自动使其处于活动状态或不活动状态。我尝试使用这两种方式来实现 Location Observer。它有效,并且在更新位置时显示 Toast 2 次。
我的问题是,如果我真的想实现数据库连接、GPS 定位、下载图像、运行 后台服务等功能,这两种方式有什么区别。我可以只使用 LiveData class 吗?因为我只需要实现active和inactive函数。
LocationLiveData.java
public class LocationLiveData extends LiveData<Location> {
private LocationManager locationManager;
private Context context;
public LocationLiveData(Context context) {
this.context = context;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
setValue(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
@Override
protected void onActive() {
super.onActive();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
@Override
protected void onInactive() {
super.onInactive();
locationManager.removeUpdates(locationListener);
}
}
MyLocationListener.java
public class MyLocationListener implements LifecycleObserver {
private LocationManager locationManager;
private Context context;
private LocationListener locationListener;
public MyLocationListener(LifecycleActivity lifecycleActivity, LocationListener callback) {
// ...
this.context = lifecycleActivity;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationListener = callback;
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
locationManager.removeUpdates(locationListener);
}
}
ComponentActivity.java
public class ComponentActivity extends LifecycleActivity {
public static final int REQUEST_CODE = 200;
private MyLocationListener myLocationListener;
public static class MyLiveData extends ViewModel {
private LocationLiveData locationLiveData;
public void init(Context context) {
locationLiveData = new LocationLiveData(context);
}
public LocationLiveData getLocationLiveData() {
return locationLiveData;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_component);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
//use the live data observer
MyLiveData myLiveData = ViewModelProviders.of(this).get(MyLiveData.class);
myLiveData.init(this);
myLiveData.getLocationLiveData().observe(this, new Observer<Location>() {
@Override
public void onChanged(@Nullable Location s) {
Toast.makeText(ComponentActivity.this, String.format("Lat : %.2f, Lon : %.2f", s.getLongitude(), s.getLatitude()), Toast.LENGTH_SHORT).show();
}
});
//use the life cycle observer
getLifecycle().addObserver(new MyLocationListener(this, new LocationListener() {
@Override
public void onLocationChanged(Location s) {
Toast.makeText(ComponentActivity.this, String.format("Lat : %.2f, Lon : %.2f", s.getLongitude(), s.getLatitude()), Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}));
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 200: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
它们是完全不同的东西,扮演着两个不同的角色。简而言之,
LifeCycle
以有效且简单的方式解决了 Android 生命周期问题。它有两个主要部分。 LifecycleOwner
公开其状态变化,LifecycleObserver
监听这些变化以做出适当的步骤。
另一方面,LiveData
利用反应式编程帮助我们轻松操作数据。它与 Java 8
中的 Stream
和 RxJava
中的 Observer
(或 Flowable
)有一些相似之处。但是,LiveData 的一个优点是它具有特定于 Android 的生命周期感知能力。因此,它与 LifeCycle 组件密切配合。
从更高的抽象层次上,我认为:
- LiveData 是一个存放一些数据的数据容器,区别在于它是 LifeCycle Aware。所以它是一个可观察的数据持有者,而不是一个观察者!
- LifecycleObserver 另一方面是一个关注的观察者
生命周期。
我认为这是主要区别。
- LifecycleOwner ------------> LifecycleObserver
在上面的箭头图中,没有涉及数据。有一个 LifecyclerOwner 其 Lifecycle 是公开的,然后有一个 LifecycleObserver 将观察任何 LifecycleOwner 状态的变化。
- LifecycleOwner ------------> LiveData ------------> 观察者
在上面的箭头图中,LiveData 是一个 Data Holder,它接受 LifecycleOwner 的上下文,它应该处理其生命周期,然后它将任何数据更改发送给 Observer (这个 Observer 不是 LifecycleObserver 但 它是一个数据观察者 )只有当 LifecycleOwner 在 onStarted或 onResumed 状态。
我已经阅读了android官方文档中关于Life Cycle and Live Data的文档。我知道 class 实现了 LifeCycleObserver 并自动关闭或打开位置侦听器。我也知道实时数据可以自动使其处于活动状态或不活动状态。我尝试使用这两种方式来实现 Location Observer。它有效,并且在更新位置时显示 Toast 2 次。
我的问题是,如果我真的想实现数据库连接、GPS 定位、下载图像、运行 后台服务等功能,这两种方式有什么区别。我可以只使用 LiveData class 吗?因为我只需要实现active和inactive函数。
LocationLiveData.java
public class LocationLiveData extends LiveData<Location> {
private LocationManager locationManager;
private Context context;
public LocationLiveData(Context context) {
this.context = context;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
setValue(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
@Override
protected void onActive() {
super.onActive();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
@Override
protected void onInactive() {
super.onInactive();
locationManager.removeUpdates(locationListener);
}
}
MyLocationListener.java
public class MyLocationListener implements LifecycleObserver {
private LocationManager locationManager;
private Context context;
private LocationListener locationListener;
public MyLocationListener(LifecycleActivity lifecycleActivity, LocationListener callback) {
// ...
this.context = lifecycleActivity;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationListener = callback;
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
locationManager.removeUpdates(locationListener);
}
}
ComponentActivity.java
public class ComponentActivity extends LifecycleActivity {
public static final int REQUEST_CODE = 200;
private MyLocationListener myLocationListener;
public static class MyLiveData extends ViewModel {
private LocationLiveData locationLiveData;
public void init(Context context) {
locationLiveData = new LocationLiveData(context);
}
public LocationLiveData getLocationLiveData() {
return locationLiveData;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_component);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
//use the live data observer
MyLiveData myLiveData = ViewModelProviders.of(this).get(MyLiveData.class);
myLiveData.init(this);
myLiveData.getLocationLiveData().observe(this, new Observer<Location>() {
@Override
public void onChanged(@Nullable Location s) {
Toast.makeText(ComponentActivity.this, String.format("Lat : %.2f, Lon : %.2f", s.getLongitude(), s.getLatitude()), Toast.LENGTH_SHORT).show();
}
});
//use the life cycle observer
getLifecycle().addObserver(new MyLocationListener(this, new LocationListener() {
@Override
public void onLocationChanged(Location s) {
Toast.makeText(ComponentActivity.this, String.format("Lat : %.2f, Lon : %.2f", s.getLongitude(), s.getLatitude()), Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}));
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 200: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
它们是完全不同的东西,扮演着两个不同的角色。简而言之,
LifeCycle
以有效且简单的方式解决了 Android 生命周期问题。它有两个主要部分。LifecycleOwner
公开其状态变化,LifecycleObserver
监听这些变化以做出适当的步骤。
另一方面,LiveData
利用反应式编程帮助我们轻松操作数据。它与Java 8
中的Stream
和RxJava
中的Observer
(或Flowable
)有一些相似之处。但是,LiveData 的一个优点是它具有特定于 Android 的生命周期感知能力。因此,它与 LifeCycle 组件密切配合。
从更高的抽象层次上,我认为:
- LiveData 是一个存放一些数据的数据容器,区别在于它是 LifeCycle Aware。所以它是一个可观察的数据持有者,而不是一个观察者!
- LifecycleObserver 另一方面是一个关注的观察者 生命周期。
我认为这是主要区别。
- LifecycleOwner ------------> LifecycleObserver
在上面的箭头图中,没有涉及数据。有一个 LifecyclerOwner 其 Lifecycle 是公开的,然后有一个 LifecycleObserver 将观察任何 LifecycleOwner 状态的变化。
- LifecycleOwner ------------> LiveData ------------> 观察者
在上面的箭头图中,LiveData 是一个 Data Holder,它接受 LifecycleOwner 的上下文,它应该处理其生命周期,然后它将任何数据更改发送给 Observer (这个 Observer 不是 LifecycleObserver 但 它是一个数据观察者 )只有当 LifecycleOwner 在 onStarted或 onResumed 状态。