我正在尝试编码一个快速的应用程序,给我所需的3G值,当我点击一个按钮。但是首先我需要检查一下我是否连接到了3G网络。但是,我的权限有一些问题。我有以下代码:
public void calculate(View view) {
TextView rscp = (TextView) findViewById(R.id.RSCP);
TextView rssi = (TextView) findViewById(R.id.RSSI);
TextView ecno = (TextView) findViewById(R.id.EcNo);
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (Arrays.stream(values_3G).anyMatch(n -> n == tm.getDataNetworkType())) {
for (CellInfo cellInfo : tm.getAllCellInfo()) {
if (cellInfo instanceof CellInfoWcdma) {
CellSignalStrengthWcdma cellSignalStrength = ((CellInfoWcdma) cellInfo).getCellSignalStrength();
rscp.setText(cellSignalStrength.getDbm());
ecno.setText(cellSignalStrength.getEcNo());
int rssiValue = -113 + 2 * cellSignalStrength.getAsuLevel();
rssi.setText(rssiValue);
}
}
} else {
rscp.setText(0);
rssi.setText(0);
ecno.setText(0);
Log.i(TAG, "No 3G Mobile connection detected!");
Toast.makeText(getApplicationContext(), "Connect to 3G", Toast.LENGTH_SHORT).show();
}
}关于READ_PHONE_STATE,tm.getDataNetworkType()给了我以下问题:
Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException如果我在Android Studio中按照说明检查权限,得到的结果如下:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}我需要在括号之间填写什么?
发布于 2021-01-08 06:11:38
创建权限请求代码的全局最终int
final int PHONE_REQUEST_CODE = 101;如果未授予权限,则请求权限
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},
PHONE_REQUEST_CODE); // triggers onRequestPermissionsResult()
} else {
// calculate(myView); // Do whatever you want as the permission is already granted
}并在活动中重写onRequestPermissionsResult()
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length == 0)
return;
if (requestCode == PHONE_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// calculate(myView); // Do whatever you want after the permission is granted
}并在manifest.xml中添加权限。
<uses-permission android:name="android.permission.READ_PHONE_STATE" />https://stackoverflow.com/questions/65620485
复制相似问题