写文件到sd卡中,会报权限问题,需要动态申请申请运行时权限
1. MainActivity.java
public class MainActivity extends Activity { private final static String TAG = "MainActivity11";private final static int EXTERNAL_STORAGE_REQUEST_CODE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, EXTERNAL_STORAGE_REQUEST_CODE); } else { // 已经授权了,第二次就可以正常写卡操作了 } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case EXTERNAL_STORAGE_REQUEST_CODE: // 用户点击权限对话框,确认后,会回调到这里,然后进行写卡操作 break; } } }
2.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.mdm" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="25" android:targetSdkVersion="25" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>