我尝试在运行时请求权限,就像android developer page中解释的那样。
但它对我不起作用。我只得到我的解释对话。没有授予或拒绝许可的对话框。
我的活动代码如下:
package de.gerding.test.dbperformancemessung;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import de.gerding.test.dbperformancemessung.Diagramme.ShowSizeGraphActivity;
import de.gerding.test.dbperformancemessung.Diagramme.ShowTimeGraphActivity;
public class MainActivity extends Activity implements View.OnClickListener
{
//View Elemente
private Button button_mainactivity_start_evaluation,button_mainactivity_show_ergebniise,button_mainactivity_show_timegraph,button_mainactivity_show_sizegraph;
private TextView textview_mainactivity_state_display;
//Debug Parameter
public static boolean logging = true;
//Ergebnisse
private long[] couchdurations = null; //= new long[]{134,56,396,970,1943};
private long[] couchsizes = null;
private long[] perstdurations = null; //= new long[]{38, 283, 546, 1445,2719};
private long[] perstsizes = null;
private long[] sqlitedurations = null; //= new long[]{60,447,4538,11523,19981};
private long[] sqlitesizes = null;
//Sonstige Variablen
private Context ctx;
private int progressstate = 0;
private final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1001;
private Activity thisActivity;
//Servicezeugs
public static String ServiceResponseTag = "ServiceResponse";
public static final String CouchTimesTag = "couchtimes";
public static final String CouchSizesTag = "couchsizes";
public static final String PerstTimesTag = "persttimes";
public static final String PerstSizesTag = "perstsizes";
public static final String SQLiteTimesTag = "sqlitetimes";
public static final String SQLiteSizesTag = "sqlitesizes";
private ResponseReceiver responsereceiver;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
thisActivity = this;
button_mainactivity_start_evaluation = (Button) findViewById(R.id.button_mainactivity_start_evaluation);
button_mainactivity_start_evaluation.setOnClickListener(this);
button_mainactivity_show_ergebniise = (Button) findViewById(R.id.button_mainactivity_show_ergebnisse);
button_mainactivity_show_ergebniise.setOnClickListener(this);
button_mainactivity_show_timegraph = (Button) findViewById(R.id.button_mainactivity_show_timediagram);
button_mainactivity_show_timegraph.setEnabled(false);
button_mainactivity_show_timegraph.setOnClickListener(this);
button_mainactivity_show_sizegraph = (Button) findViewById(R.id.button_mainactivity_show_dbsizediagram);
button_mainactivity_show_sizegraph.setEnabled(false);
button_mainactivity_show_sizegraph.setOnClickListener(this);
ctx = this;
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
checkPermissions();
}
@Override
public void onClick(View v)
{
log("Gerding", "onClick(View v");
Intent intent;
switch (v.getId())
{
case R.id.button_mainactivity_start_evaluation:
log("Gerding", "Start Evaluation");
intent = new Intent(this, EvaluationService.class);
this.startService(intent);
//ergebnisArraysInitialisieren();
progressstate = 0;
progressDialog = new ProgressDialog(ctx);
progressDialog.setMax(28);
progressDialog.setProgress(0);
progressDialog.setTitle("Evaluation läuft");
progressDialog.setMessage("Evaluation wurde gestartet");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.show();
button_mainactivity_show_timegraph.setEnabled(false);
button_mainactivity_show_sizegraph.setEnabled(false);
//initData();
break;
case R.id.button_mainactivity_show_timediagram:
log("Gerding", "Show TimeGraph");
if((couchdurations != null) && (perstdurations != null) && (sqlitedurations != null))
{
intent = new Intent(this, ShowTimeGraphActivity.class);
intent.putExtra(MainActivity.CouchTimesTag, couchdurations);
intent.putExtra(MainActivity.PerstTimesTag, perstdurations);
intent.putExtra(MainActivity.SQLiteTimesTag, sqlitedurations);
startActivity(intent);
}else
{
Toast.makeText(ctx, "Es muss erst evaluiert werden", Toast.LENGTH_LONG).show();
}
break;
case R.id.button_mainactivity_show_dbsizediagram:
if((couchdurations != null) && (perstdurations != null) && (sqlitedurations != null))
{
intent = new Intent(this, ShowSizeGraphActivity.class);
intent.putExtra(MainActivity.CouchSizesTag, couchsizes);
intent.putExtra(MainActivity.PerstSizesTag, perstsizes);
intent.putExtra(MainActivity.SQLiteSizesTag, sqlitesizes);
startActivity(intent);
}else
{
Toast.makeText(ctx, "Es muss erst evaluiert werden", Toast.LENGTH_LONG).show();
}
break;
case R.id.button_mainactivity_show_ergebnisse:
intent = new Intent(this, ErgebnisActivity.class);
intent.putExtra(MainActivity.CouchTimesTag, couchdurations);
intent.putExtra(MainActivity.CouchSizesTag, couchsizes);
intent.putExtra(MainActivity.PerstTimesTag, perstdurations);
intent.putExtra(MainActivity.PerstSizesTag, perstsizes);
intent.putExtra(MainActivity.SQLiteTimesTag, sqlitedurations);
intent.putExtra(MainActivity.SQLiteSizesTag, sqlitesizes);
startActivity(intent);
}
}
public class ResponseReceiver extends BroadcastReceiver
{
public static final String ACTION_RESP = "de.gerding.intent.action.serviceanswer";
@Override
public void onReceive(Context context, Intent intent)
{
if(intent.getStringExtra(ServiceResponseTag).equalsIgnoreCase("State"))
{
progressstate ++;
if(progressDialog.isShowing())
{
progressDialog.setMessage(intent.getStringExtra("State"));
progressDialog.setProgress(progressstate);
}
log("Gerding", "new State: " + intent.getStringExtra("State"));
}else if(intent.getStringExtra(ServiceResponseTag).equalsIgnoreCase("ENDE"))
{
if(progressDialog.isShowing())
{
progressDialog.dismiss();
}
button_mainactivity_show_timegraph.setEnabled(true);
button_mainactivity_show_sizegraph.setEnabled(true);
couchdurations = intent.getLongArrayExtra(MainActivity.CouchTimesTag);
couchsizes = intent.getLongArrayExtra(MainActivity.CouchSizesTag);
perstdurations = intent.getLongArrayExtra(MainActivity.PerstTimesTag);
perstsizes = intent.getLongArrayExtra(MainActivity.PerstSizesTag);
sqlitedurations = intent.getLongArrayExtra(MainActivity.SQLiteTimesTag);
sqlitesizes = intent.getLongArrayExtra(MainActivity.SQLiteSizesTag);
new writeToFileTask().execute();
intent = new Intent(ctx, ErgebnisActivity.class);
intent.putExtra(MainActivity.CouchTimesTag, couchdurations);
intent.putExtra(MainActivity.CouchSizesTag, couchsizes);
intent.putExtra(MainActivity.PerstTimesTag, perstdurations);
intent.putExtra(MainActivity.PerstSizesTag, perstsizes);
intent.putExtra(MainActivity.SQLiteTimesTag, sqlitedurations);
intent.putExtra(MainActivity.SQLiteSizesTag, sqlitesizes);
startActivity(intent);
}
}
}
@Override
protected void onPause()
{
super.onPause();
unregisterReceiver(responsereceiver);
}
@Override
protected void onStop()
{
super.onStop();
}
@Override
protected void onResume()
{
super.onResume();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
responsereceiver = new ResponseReceiver();
registerReceiver(responsereceiver, filter);
}
public static void log(String logTag, String logtext)
{
if(logging)
{
Log.i(logTag, logtext);
}
}
private class writeToFileTask extends AsyncTask<String, Integer, Long>
{
protected Long doInBackground(String... params)
{
Log.i("Gerding", "Filewrite is started");
//Write File
String state;
File file;
state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state))
{
File Root = Environment.getExternalStorageDirectory();
File Dir = new File(Root.getAbsolutePath()+"/DBEvaluation");
if(!Dir.exists())
{
Dir.mkdir();
}
//Datetime
Date date = new Date();
SimpleDateFormat simpleDate = new SimpleDateFormat("dd_MM_yy_HH_mm_ss");
String filename = simpleDate.format(date);
file = new File(Dir, filename + ".txt");
FileOutputStream fos = null;
String zeile = "";
long[] datasizes = new long[]{
10000,
10000,
10000,
10000,
10000,
1000,
10000,
100000};
try {
fos = new FileOutputStream(file);
zeile = "Fahrt\tDatensätze\tCouchbase\tPerst\tSQLite\n";
fos.write(zeile.getBytes());
for(int i = 0; i < 8; i++)
{
zeile = (i+1) + "\t" + datasizes[i]+ "\t" + couchdurations[0] + "\t" + perstdurations[0] + "\t" + sqlitedurations[i] + "\n";
fos.write(zeile.getBytes());
}
zeile = "\n\n";
fos.write(zeile.getBytes());
zeile = "Fahrt\tDatensätze\tCouchbase\tPerst\tSQLite\n";
fos.write(zeile.getBytes());
for(int i = 0; i < 8; i++)
{
zeile = (i+1) + "\t" + datasizes[i]+ "\t" + couchsizes[0] + "\t" + perstsizes[0] + "\t" + sqlitesizes[i] + "\n";
fos.write(zeile.getBytes());
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else
{
//ERROR
}
Log.i("Gerding", "Filewrite is finished");
return 0l;
}
}
public void checkPermissions()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
// No explanation needed, we can request the permission.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Zugriff auf den externen Speicher wird benötigt um Daten in eine Datei schreiben zu können.").setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
//do things
ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
});
AlertDialog alert = builder.create();
alert.show();
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
//}
}
/*// Quick permission check
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}*/
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch (requestCode)
{
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
// permission was granted, yay! Do the
// task you need to do.
}else
{
// permission denied, boo! Disable the
// functionality that depends on this permission.
this.finish();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
有什么问题?