• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

java - Android 应用架构 : Implements user permission in lifecycle

[复制链接]
菜鸟教程小白 发表于 2022-12-9 06:48:28 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我有一个 LocationListener,它是 LiveData 类的扩展。从 Android 6.0 开始,权限是在运行时请求的。现在,当我尝试实现 LiveData 类时,它需要在 onActive() 函数中进行权限检查。 我必须在每个 Activity 中为请求的权限和收到的结果制作样板代码。有没有办法移动这样的 onRequestPermissionsResult()checkSelfPermission() 函数到 LocationListener ?

LocationFragment.java

public class LocationFragment extends LifecycleFragment {

  private FragmentLocationBinding binding;


  public LocationFragment() {
    // Required empty public constructor
  }


  @Override
  public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (ContextCompat.checkSelfPermission(getActivity(),
        permission.ACCESS_COARSE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
      // Should we show an explanation?
      if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
          Manifest.permission.ACCESS_COARSE_LOCATION)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

      } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(getActivity(),
            new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
            200);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
      }
    }
    //get the viewmodel from activity
    LastLocationViewModel lastLocationViewModel = ViewModelProviders.of(getActivity())
        .get(LastLocationViewModel.class);
    lastLocationViewModel.getLastKnowLocation().observe(this, location -> {
      binding.setLocation(location);
    });

  }

  @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) {
          Toast.makeText(getActivity(), "Rights Granted", Toast.LENGTH_SHORT).show();
          // 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
    }
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    binding = DataBindingUtil
        .inflate(LayoutInflater.from(getActivity()), R.layout.fragment_location, null, false);
    return binding.getRoot();
  }

}

LastLocationListener.java

public class LastLocationListener extends LiveData<Location> {

  private LocationManager locationManager;

  private Context context;

  private LocationListener listener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {

      Log.d("Location Msg", location.toString());
      setValue(location);
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
  };

  public LastLocationListener(Context context) {
    this.context = context;
    locationManager = (LocationManager) context.getSystemService(
        Context.LOCATION_SERVICE);
  }

  @Override
  protected void onActive() {
    if (ActivityCompat.checkSelfPermission(context, permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(context, 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.NETWORK_PROVIDER, 0, 0, listener);
  }

  @Override
  protected void onInactive() {
    locationManager.removeUpdates(listener);
  }


}



Best Answer-推荐答案


when I tried to implements the LiveData Class and it required the permission checking in onActive() function

不,它没有。你看到的是一个 Lint 警告,你可以抑制它。 要求您在尝试使用 LiveData 的这一特定位之前持有该权限。

Is there any way to move such onRequestPermissionsResult() and checkSelfPermission() functions to the LocationListener ?

没有。

关于java - Android 应用架构 : Implements user permission in lifecycle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46108179/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap