You are going to need to use the UIAutomator framework to press yes
when the permission popup shows up in a testing environment. The following snippet is taken from this medium post, make sure you check it out.
private void allowPermissionsIfNeeded() {
if (Build.VERSION.SDK_INT >= 23) {
UiObject allowPermissions = mDevice.findObject(new UiSelector().text("Allow"));
if (allowPermissions.exists()) {
try {
allowPermissions.click();
} catch (UiObjectNotFoundException e) {
Timber.e(e, "There is no permissions dialog to interact with ");
}
}
}
}
You probably need to ask for permissions at runtime since you are running it on an Android device with API 23.
Check on this link to see the full documentation on how to do it.
Following is a small example that shows how to ask for permissions to read the call log in a device. You would have to change a bit the logic to ask for WRITE_EXTERNAL_STORAGE
instead of the READ_CALL_LOG
permission.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivityTAG_";
private static final int CODE_CALL_LOG = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CALL_LOG)) {
Log.d(TAG, "onCreate: " + "Show explanation");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALL_LOG}, CODE_CALL_LOG);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALL_LOG}, CODE_CALL_LOG);
}
} else {
Log.d(TAG, "onCreate: " + "Permission already granted!");
printCallLog();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case CODE_CALL_LOG: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "onRequestPermissionsResult: Good to go!");
printCallLog();
} else {
Log.d(TAG, "onRequestPermissionsResult: Bad user");
}
}
}
}
private void printCallLog() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED) {
Cursor cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI,
null,
null,
null,
null);
while (cursor.moveToNext()) {
final long dateDialed = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
final String numberDialed = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
Log.d(TAG, "Call to number: " + numberDialed + "\t registered at: " + new Date(dateDialed).toString());
}
cursor.close();
}
}
}
This is the link with the full GitHub project.