Android 7.1 Write to text file

孤者浪人 提交于 2019-12-01 14:27:13

Either you have the permission and can do the try catch block where you write into the file or you have to do it in the onRequestPermissionsResult.

Something like :

public void yourMethod(){
    boolean hasPermission = (ContextCompat.checkSelfPermission(data_entry.this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    if(hasPermission){
      // write
    }else{
      // ask the permission
      ActivityCompat.requestPermissions(data_entry.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_WRITE_STORAGE);
      // You have to put nothing here (you can't write here since you don't
      // have the permission yet and requestPermissions is called asynchronously)
   }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    // The result of the popup opened with the requestPermissions() method
    // is in that method, you need to check that your application comes here
    if (requestCode == REQUEST_WRITE_STORAGE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // write
        }
    }
}

I suggest that you check this link : https://developer.android.com/training/permissions/requesting.html

This is what you need: https://developer.android.com/training/articles/scoped-directory-access.html#accessing

You have to ask the user to give the rights to access it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!