package de.abc.trytowriteonmicrosd;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
static final int REQUEST_EXTERNAL_STORAGE_RESULT = 2;
String dasWirdDieNachricht = "Hallo";
String filename = "Hi.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Überprüfe ob Berechtigung vorhanden
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
Log.i("MainActvity", "Permission grant save now!");
//Datei speichern
save();
}
else{
Log.i("MainActvity", "No Permission, request it!");
// Berechtigung abfragen
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_EXTERNAL_STORAGE_RESULT);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
//Überprüfen welcher Request/Berechtigung ankam
switch (requestCode) {
case REQUEST_EXTERNAL_STORAGE_RESULT: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Berechtigung bekommen, save aufrufen
Log.i("MainActvity", "Permission grant save now!");
save();
} else {
//Berechtigung nicht bekommen
Log.i("MainActvity", "Failed to get Permission!");
}
}
}
}
public void save() {
Log.i("MainActvity", "Save called!");
//Primären externe Pfad bekommen
File root = Environment.getExternalStorageDirectory();
//Alle externe Pfade bekommen
File[] externalFilesDir = getExternalFilesDirs(null);
for(File externalFileDir : externalFilesDir){
Log.i("MainActvity", "File-Dir: " + externalFileDir.getAbsolutePath());
}
//Wenn SD Karte vorhanden, dann sd-karte setzen (statt dem primären)
if(externalFilesDir.length > 1){
root = externalFilesDir[1];
}
File writeFile = new File(root, filename);
Log.i("MainActvity", "Save Path: " + writeFile.getAbsolutePath());
//Überprüfe ob Datei schon existiert
if(!writeFile.exists()) {
//Schreibe Datei
try {
FileOutputStream fos = new FileOutputStream(writeFile);
fos.write(dasWirdDieNachricht.getBytes());
fos.close();
Log.i("MainActvity", "File saved!");
} catch (IOException e) {
e.printStackTrace();
}
}
else{
Log.i("MainActvity", "File already exists!");
}
}
}
Alles anzeigen