activity_main.xml
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tv"/>
AndroidManifest.xml
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView tv;
private TelephonyManager telephonyManager;
private MyPhoneStateListener mListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.tv);
telephonyManager= (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mListener=new MyPhoneStateListener();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_NETWORK_STATE)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CHANGE_NETWORK_STATE},1);
}else {
telephonyManager.listen(mListener,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
}
@Override
public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults){
switch (requestCode){
case 1:
if (grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
telephonyManager.listen(mListener,LISTEN_SIGNAL_STRENGTHS);
}else {
Toast.makeText(this,"You denied permissions",Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
//PhoneStateListener
private class MyPhoneStateListener extends PhoneStateListener{
private int asu=0,lastSignal=0;
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
super.onSignalStrengthsChanged(signalStrength);
asu=signalStrength.getGsmSignalStrength();
lastSignal=-113+2*asu;
Log.d("asu", String.valueOf(asu));
Log.d("signal", String.valueOf(lastSignal));
tv.setText("the current signal strength:"+lastSignal+"dBm");
}
}
}
网友评论