AndroidManifest.xml增加
</application>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
private void checkPermission() {
//检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//用户已经拒绝过一次,再次弹出权限申请对话框需要给用户一个解释
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "请开通相关权限,否则无法正常使用本应用!", Toast.LENGTH_SHORT).show();
}
//申请权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
Toast.makeText(this, "授权成功!", Toast.LENGTH_SHORT).show();
//Log.e(TAG_SERVICE, "checkPermission: 已经授权!");
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
checkPermission();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Snackbar.make(view, R.string.app_name, Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
try {
String sdCardDir = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(sdCardDir,"output.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file);
PrintWriter pw = new PrintWriter(writer, true);
pw.println("科技刻录机");
pw.println("明月浪");
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
String sdCardDir = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(sdCardDir,"output.txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
String line = in.readLine();
Snackbar.make(view, line, Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}