/**
* 1.先检查权限有没有授权过,如果授权过不申请,如果没有就去申请
* 2.如果去申请用户拒绝了,发起二次请求,此时会有一个“不在提示的”选择
* 3.在二次请求中,这里需要给用户解释一下我们为什么需要这个权限,否则用户可能会永久不在激活这个申请,方便用户理解我们为什么需要这个权限
* 4.如果用户二次请求被拒绝或者选择了不在提示,我们引导用户到应用权限页面,让用户自己手动打
*/
权限包装类:
public class SplashActivity extends AppCompatActivity {
private RelativeLayout mRelayBg;
private PermissionHelper.PermissionModel[] permissionModels = {
new PermissionHelper.PermissionModel(1, Manifest.permission.READ_PHONE_STATE, "我们需要读取手机状态,来识别你的身份"),
new PermissionHelper.PermissionModel(0, Manifest.permission.CAMERA, "我们需要获取一些图片资源")
};
private PermissionHelper permissionHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
mRelayBg = (RelativeLayout) findViewById(R.id.relay_splash);
permissionHelper = new PermissionHelper(this);
permissionHelper.setOnAlterApplyPermission(new PermissionHelper.OnAlterApplyPermission() {
@Override
public void OnAlterApplyPermission() {
runApp();
}
});
permissionHelper.setRequestPermission(permissionModels);
if (Build.VERSION.SDK_INT < 23) {//6.0以下,不需要动态申请
runApp();
} else {//6.0+ 需要动态申请
//判断是否全部授权过
if (permissionHelper.isAllApplyPermission()) {//申请的权限全部授予过,直接运行
runApp();
} else {//没有全部授权过,申请
permissionHelper.applyPermission();
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
permissionHelper.onActivityResult(requestCode, resultCode, data);
}
/**
* 程序的正常执行流程
*/
private void runApp() {
AlphaAnimation anim = new AlphaAnimation(1f, 0.5f);
anim.setDuration(3000);
anim.setFillAfter(true);
mRelayBg.startAnimation(anim);
anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
}
实现类:
package com.gfd.permission;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
/**
* 类描述:权限申请帮助类
* 创建日期: 2017/3/20 0020 下午 4:36
* 更新日期:
*/
public class PermissionHelper {
private PermissionModel[] permissionModels;
private Activity activity;
private OnAlterApplyPermission listener;
public PermissionHelper(Activity activity) {
this.activity = activity;
}
public void setRequestPermission(PermissionModel[] models) {
this.permissionModels = models;
}
/**
* 申请的权限是否全部授予过
*
* @return true:全部授予了
*/
public boolean isAllApplyPermission() {
if (permissionModels != null && permissionModels.length != 0) {
for (PermissionModel permissionModel : permissionModels) {
if (ContextCompat.checkSelfPermission(activity, permissionModel.permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
return false;
}
/**
* 动态申请权限
*/
public void applyPermission() {
for (PermissionModel permissionModel : permissionModels) {
//如果没有授予过,再申请
if (ContextCompat.checkSelfPermission(activity, permissionModel.permission) != PackageManager.PERMISSION_GRANTED) {
//申请
ActivityCompat.requestPermissions(activity, new String[]{permissionModel.permission}, permissionModel.requestCode);
return;
}
}
if (listener != null) listener.OnAlterApplyPermission();
}
/**
* 根据权限获取对应的说明
*
* @param permission
* @return
*/
private String findPermissionExplain(String permission) {
for (PermissionModel permissionModel : permissionModels) {
if (permissionModel.permission.equals(permission)) {
return permissionModel.explain;
}
}
return "";
}
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {//用户没有同意
//二次申请,二次申请的时候回多一个"不再提示"的checkBox
//二次申请的时候需要告诉用户为什么需要这权限
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permissions[0])) {//用户拒绝了
AlertDialog.Builder builder = new AlertDialog.Builder(activity).setTitle("权限申请")
.setMessage(findPermissionExplain(permissions[0]))
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
applyPermission();
}
});
builder.setCancelable(false);
builder.show();
} else {
//引导用户去应用设置页面手动开启权限
AlertDialog.Builder builder = new AlertDialog.Builder(activity).setTitle("权限申请")
.setMessage("在应用设置页面打开:" + findPermissionExplain(permissions[0]) + "权限")
.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
openAppPermissionSettrings();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
activity.finish();
}
});
builder.setCancelable(false);
builder.show();
}
return;
}
if (isAllApplyPermission() && listener != null) {
listener.OnAlterApplyPermission();
} else {
applyPermission();
}
}
/**
* 打开应用的设置界面
*/
private void openAppPermissionSettrings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + activity.getPackageName()));
intent.addCategory(Intent.CATEGORY_DEFAULT);
activity.startActivityForResult(intent, 3);
}
public static class PermissionModel {
String permission;
String explain;
int requestCode;
public PermissionModel(int requestCode, String permission,String explain) {
this.permission = permission;
this.explain = explain;
this.requestCode = requestCode;
}
}
public void setOnAlterApplyPermission(OnAlterApplyPermission listener) {
this.listener = listener;
}
public interface OnAlterApplyPermission {
void OnAlterApplyPermission();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (isAllApplyPermission() && listener != null) {
listener.OnAlterApplyPermission();
} else {
applyPermission();
}
}
}
源码地址:https://github.com/applelili/SettingAuthour
===========================================
XML操作:
源码地址:与权限相同
package com.gfd.xml;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Xml;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
/** XML文件操作测试类 */
@RunWith(AndroidJUnit4.class)
public class XmlTest {
private List<Person> persons;
private Context context;
@Before
public void init(){
context = InstrumentationRegistry.getTargetContext();
persons = new ArrayList<>();
persons.add(new Person(40,1,"林志玲","女"));
persons.add(new Person(50,2,"刘德华","男"));
persons.add(new Person(45,3,"林心如","女"));
persons.add(new Person(42,4,"范冰冰","女"));
persons.add(new Person(40,5,"郭富东","男"));
}
/* XML序列化 */
@Test
public void serialize(){
try {
//指定存储的路径
File outFile = new File(context.getFilesDir() + "/person.xml");
XmlSerializer serializer = Xml.newSerializer();//获取xml序列化对象
FileOutputStream out = new FileOutputStream(outFile);
serializer.setOutput(out,"UTF-8");
serializer.startDocument("UTF-8",true);//设置文档的开始
serializer.startTag(null,"persons");
for (Person person : persons) {
serializer.startTag(null,"person");
serializer.attribute(null,"id",person.getId() + "");
//写name标签
serializer.startTag(null,"name");
serializer.text(person.getName());
serializer.endTag(null,"name");
//age标签
serializer.startTag(null,"age");
serializer.text(person.getAge() + "");
serializer.endTag(null,"age");
//sex标签
serializer.startTag(null,"sex");
serializer.text(person.getSex());
serializer.endTag(null,"sex");
//写一组的结束标签
serializer.endTag(null,"person");
}
serializer.endTag(null,"persons");
serializer.endDocument();
serializer.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/* Xml解析
* Java:
* DOM :会把整个文件加载到内存中,仔解析,不适合大文件
* SAX :基于事件的,可以一个一个的解析
* Android新增:
* PULL :跟SAX类似
* */
@Test
public void pullParser(){
try {
//指定读取的路径
File inFile = new File(context.getFilesDir() + "/person.xml");
if(!inFile.exists())return;
XmlPullParser parser = Xml.newPullParser();//获取解析xml的对象
parser.setInput(new FileInputStream(inFile),"UTF-8");
int eventType = parser.getEventType();//获取解析的事件类型
List<Person> persons = null;
Person person = null;
while (eventType != XmlPullParser.END_DOCUMENT){//不是文档的结尾就解析
switch (eventType){
case XmlPullParser.START_TAG://开始标签
String tagName = parser.getName();
if(tagName.equals("persons")){//开始解析
persons = new ArrayList<>();
}else if(tagName.equals("person")){
person = new Person();
person.setId(Integer.parseInt(parser.getAttributeValue(null,"id")));//获取标签内的属性
}else if(tagName.equals("name")){
person.setName(parser.nextText());
}else if(tagName.equals("age")){
person.setAge(Integer.parseInt(parser.nextText()));
}else if(tagName.equals("sex")){
person.setSex(parser.nextText());
}
break;
case XmlPullParser.END_TAG://结束标签
String endTag = parser.getName();
if(endTag.equals("person")){//一个数据解析完毕,添加到集合里面
persons.add(person);
person = null;
}
break;
}
//开始下一个
eventType = parser.next();
}
//打印集合中的数据
for (Person person1 : persons) {
System.out.println(person1.toString());
}
} catch(Exception e) {
e.printStackTrace();
}
}
}