当权限弹出窗口出现在测试环境中时,您将需要使用UIAutomator框架来按下。yes
以下片段摘自此中型帖子,请务必查看。
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 ");
}
}
}
}
您可能需要在运行时请求权限,因为您在使用 API 23 的 Android 设备上运行它。
检查此链接以查看有关如何执行此操作的完整文档。
以下是一个小示例,展示了如何请求权限以读取设备中的通话记录。您将不得不更改一些逻辑来请求WRITE_EXTERNAL_STORAGE
而不是READ_CALL_LOG
许可。
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();
}
}
}
这是完整 GitHub 项目的链接。