android – LiveData和LifecycleObserver之间有什么区别

android – LiveData和LifecycleObserver之间有什么区别,第1张

概述我在 android官方文档中阅读了有关 Life Cycle和 Live Data的文档.我知道该类实现了LifeCycleObserver并使位置监听器自动关闭或打开.我也知道实时数据可以自动激活或激活.我尝试使用这两种方法实现Location Observer.它工作正常,当位置更新时它显示Toast 2次. 我的问题是,这两种方式有什么区别,如果我真的想实现像DB Connection,G 我在 android官方文档中阅读了有关 Life Cycle和 Live Data的文档.我知道该类实现了lifeCycleObserver并使位置监听器自动关闭或打开.我也知道实时数据可以自动激活或激活.我尝试使用这两种方法实现Location Observer.它工作正常,当位置更新时它显示Toast 2次.

我的问题是,这两种方式有什么区别,如果我真的想实现像DB Connection,GPS Location,Download Image,运行后台服务这样的东西.我可以只使用liveData类吗?因为我只需要实现主动和非主动功能.

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,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,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,Toast.LENGTH_SHORT).show();            }            @OverrIDe            public voID onStatusChanged(String provIDer,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组件密切配合.

总结

以上是内存溢出为你收集整理的android – LiveData和LifecycleObserver之间有什么区别全部内容,希望文章能够帮你解决android – LiveData和LifecycleObserver之间有什么区别所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1135034.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-30
下一篇2022-05-30

发表评论

登录后才能评论

评论列表(0条)

    保存