需要做缓存申请系统空间使用的必须经过用户同意,否则是不能进行sd卡使用的,简单拿这个来举例说明
这个权限用户是可以进行动态关闭的,也就是你每次用到某个权限时都需要去进行相应的申请,并且根据用户不同的选择结果进行相应的操作,从而避免不必要的crash
简单写了个工具性的方法
package com.fanyafeng.testnew.MyApplication;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
/**
* Created by fanyafeng on 2015/12/25,0025.
*/
public class PermissionControl {
public static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE=0;
/**
* 以下的util在activity中调用
*/
public static boolean isGetPermissionFor(Context context, String permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
} else {
return true;
}
} else {
return true;
}
}
/**
* 以下的util在fragment中调用
* 但是如果是fragment嵌套fragment需要注意
*/
}
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">这里</span><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">着重说一下在activity和fragment和fragment中的fragment的权限申请,现在新建的activity都是继承的AppCompatActivity</span>
博主一直都是习惯写个base,因为管理起来比较容易,尤其有些可以抽出来的东西
activity中进行权限的申请
package com.fanyafeng.testnew.PermissionTest;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.fanyafeng.testnew.BaseActivity;
import com.fanyafeng.testnew.MyApplication.PermissionControl;
import com.fanyafeng.testnew.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class PermissionInActivity extends BaseActivity {
private Button btn_permission;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permisson_in);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
title = "测试activity中的权限管理";
isShowEmail=true;
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "重新给予应用权限?", Snackbar.LENGTH_LONG)
.setAction("获取权限", onClickListener).show();
}
});
initView();
requestPermission();
}
View.OnClickListener onClickListener=new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermission();
}
};
private void initView() {
btn_permission = (Button) findViewById(R.id.btn_permission);
}
private void requestPermission() {
if (PermissionControl.isGetPermissionFor(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
initData();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PermissionControl.WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
}
}
private void initData() {
btn_permission.setOnClickListener(this);
}
private void newText() {
File sdCarePath = Environment.getExternalStorageDirectory();
if (sdCarePath.exists()) {
File file = new File(sdCarePath.getPath() + File.separator + "permission");
if (!file.exists()) {
file.mkdirs();
}
String filePath = file.getPath() + File.separator + "permission.txt";
File file1 = new File(filePath);
if (!file1.exists())
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File(filePath));
String name = "樊亚风";
fileOutputStream.write(name.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null)
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
case R.id.btn_permission:
newText();
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PermissionControl.WRITE_EXTERNAL_STORAGE_REQUEST_CODE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initData();
} else {
Toast.makeText(this, "请求被拒绝,应用无法进行相应操作", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
最后重写的方法是得知用户是否同意进行相应的权限操作,requestpermission()则是判断是否应用得到了相应的操作权限,没有的话去询问用户,已经得到的话就去进行相应的操作
在fragment中进行权限操作
package com.fanyafeng.testnew.PermissionTest;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.fanyafeng.testnew.BaseActivity;
import com.fanyafeng.testnew.BaseFragment;
import com.fanyafeng.testnew.MyApplication.PermissionControl;
import com.fanyafeng.testnew.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* to handle interaction events.
* Use the {@link NestFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class NestFragment extends BaseFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Button btn_new_text_nest;
private Button btn_add_nestin;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment NestFragment.
*/
// TODO: Rename and change types and number of parameters
public static NestFragment newInstance(String param1, String param2) {
NestFragment fragment = new NestFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public NestFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_nest, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initView();
initData();
}
private void initView() {
btn_new_text_nest = (Button) getActivity().findViewById(R.id.btn_new_text_nest);
btn_add_nestin=(Button)getActivity().findViewById(R.id.btn_add_nestin);
btn_add_nestin.setOnClickListener(this);
requestpermission();
}
private void initData() {
btn_new_text_nest.setOnClickListener(this);
}
private void newText() {
File sdCardPath= Environment.getExternalStorageDirectory();
if (sdCardPath.exists()){
File file=new File(sdCardPath.getPath()+File.separator+"fragmentPer");
if (!file.exists()){
file.mkdirs();
}
String filePath=file.getPath()+File.separator+"fragmentPer.txt";
File file1=new File(filePath);
if (!file1.exists()){
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream(new File(filePath));
String name="activity中的fragment请求权限";
fileOutputStream.write(name.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (fileOutputStream!=null)
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
case R.id.btn_new_text_nest:
newText();
break;
case R.id.btn_add_nestin:
addNewFragment();
break;
}
}
private void addNewFragment(){
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
NestInFragment nestInFragment=new NestInFragment();
fragmentTransaction.setCustomAnimations(R.anim.push_left_in,R.anim.push_right_out,R.anim.push_left_in,R.anim.push_right_out);
fragmentTransaction.add(R.id.nestin_conatiner,nestInFragment,"NestInFragment");
fragmentTransaction.addToBackStack("NestInFragment");
fragmentTransaction.commit();
}
private void requestpermission(){
if (PermissionControl.isGetPermissionFor(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)){
initData();
}else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PermissionControl.WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// List<Fragment> fragmentList=getChildFragmentManager().getFragments();
// if (fragmentList!=null){
// for (Fragment fragment:fragmentList){
// if (fragment!=null){
// fragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
// }
// }
// }
switch (requestCode){
case PermissionControl.WRITE_EXTERNAL_STORAGE_REQUEST_CODE:
if (grantResults[0]== PackageManager.PERMISSION_GRANTED){
initData();
}else {
Toast.makeText(getActivity(),"请求被拒绝,应用无法进行相应操作",Toast.LENGTH_SHORT).show();
}
}
}
}
相应的list操作原本是用来测试childfragment的,博主插的资料说可以,但是经过实际操作不行
下面是childfragment获取权限操作
package com.fanyafeng.testnew.PermissionTest;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.fanyafeng.testnew.BaseFragment;
import com.fanyafeng.testnew.MyApplication.PermissionControl;
import com.fanyafeng.testnew.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* to handle interaction events.
* Use the {@link NestInFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class NestInFragment extends BaseFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Button btn_new_text_nestin;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment NestInFragment.
*/
// TODO: Rename and change types and number of parameters
public static NestInFragment newInstance(String param1, String param2) {
NestInFragment fragment = new NestInFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public NestInFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_nest_in, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initView();
requestPermission();
}
private void requestPermission() {
if (PermissionControl.isGetPermissionFor(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
initData();
} else {
// 此请求是配合此fragment内的权限请求周期使用
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PermissionControl.WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
}
}
private void initView() {
btn_new_text_nestin = (Button) getActivity().findViewById(R.id.btn_new_text_nestin);
}
private void initData() {
btn_new_text_nestin.setOnClickListener(this);
}
private void newText() {
File sdCardPath = Environment.getExternalStorageDirectory();
if (sdCardPath.exists()) {
File file = new File(sdCardPath.getPath() + File.separator + "fragmentInPer");
if (!file.exists()) {
file.mkdirs();
}
String filePath = file.getPath() + File.separator + "nestin.txt";
File file1 = new File(filePath);
if (file1.exists()) {
try {
file1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File(filePath));
String name = "fragment中的fragment请求权限";
fileOutputStream.write(name.getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null)
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
case R.id.btn_new_text_nestin:
newText();
Log.d("TAG","NestInFragment执行创建文件操作");
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PermissionControl.WRITE_EXTERNAL_STORAGE_REQUEST_CODE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initData();
} else {
Toast.makeText(getActivity(), "未获取到权限,该应用不能进行相应的操作", Toast.LENGTH_SHORT).show();
}
}
}
}
感觉在fragment和childfragment基本可以等同操作,建议大家亲自上手操作以下,这里顺便测试了一个fragment的动画以及压入弹出栈的操作
下面是github地址,可以fork或者check下来自己进行研究,xml的代码没有贴
读书随笔
ThenI realized I was really annoyed with myself for not seeing the obvious anddoing what works when things change.