android studio中双sim卡的网络参数

时间:2018-02-21 07:50:41

标签: android classcastexception

我正在创建一个显示网络参数的应用程序。当我的双卡手机上只有一个SIM卡处于活动状态时,该应用程序可以正常工作并分别显示2g,3g或4g的参数。但是当两张SIM卡都处于活动状态时,应用程序崩溃了。我应该如何编写代码以使应用程序适用于两张SIM卡而不会崩溃? 我是android studio和android编码的新手。

编辑[日志]:

FATAL EXCEPTION: main
                                                                      Process: air.newapp.airtelapp, PID: 27711
                                                                      java.lang.RuntimeException: Unable to start activity ComponentInfo{air.newapp.airtelapp/air.newapp.airtelapp.loc}: java.lang.ClassCastException: android.telephony.CellInfoGsm cannot be cast to android.telephony.CellInfoLte
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3046)
                                                                          at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1688)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                          at android.os.Looper.loop(Looper.java:164)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6809)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                       Caused by: java.lang.ClassCastException: android.telephony.CellInfoGsm cannot be cast to android.telephony.CellInfoLte
                                                                          at air.newapp.airtelapp.loc.onCreate(loc.java:74)
                                                                          at android.app.Activity.performCreate(Activity.java:6998)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1230)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2899)

编辑[代码]:

public class loc extends Activity implements LocationListener {


    LocationManager locationManager;
    String provider;
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loc);

        TelephonyManager telephonyManager;
        TelephonyManager telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        if (telephony.getNetworkType() == TelephonyManager.NETWORK_TYPE_LTE) {
            telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != 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.
                //  Toast.makeText(getBaseContext(), "If Clause : 02",
                //        Toast.LENGTH_SHORT).show();
                //   return;
            }
            //  Log.i(TAG, "onCreate: 02 ");
            TelephonyManager tels = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String networkOp = tels.getNetworkOperator();
            CellInfoLte cellInfoLte = (CellInfoLte) telephonyManager.getAllCellInfo().get(0);
            CellSignalStrengthLte cellSignalStrengthLte = cellInfoLte.getCellSignalStrength();
            int ab = cellSignalStrengthLte.getDbm();
            TextView rsp = (TextView) findViewById(R.id.rsrp);
            rsp.setText("RSRP:" + ab + "dbm");
            int aba = cellSignalStrengthLte.getRsrq();
            TextView rsrq = (TextView) findViewById(R.id.rsrq);
            rsrq.setText("RSRQ: " + aba + "db");
               /* int snr = cellSignalStrengthLte.getRssnr();
                TextView snr1 = (TextView) findViewById(R.id.rssnr1);
                snr1.setText("RSSNR:" + snr + "db");*/
            CellIdentityLte cellIdentityLte = cellInfoLte.getCellIdentity();
            int ta = cellIdentityLte.getTac();
            TextView tac = (TextView) findViewById(R.id.tac);
            tac.setText("TAC: " + ta);
            int pci = cellIdentityLte.getPci();
            TextView pcii = (TextView) findViewById(R.id.pci);
            pcii.setText("PCI: " + pci);
            TextView tech = (TextView) findViewById(R.id.tech);
            tech.setText("Technology: 4G");
            //   Log.i(TAG, "onCreate: 03 ");
            if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {

                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != 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.
                    //         Toast.makeText(getBaseContext(), "If Clause : 03",
                    //               Toast.LENGTH_SHORT).show();
                    return;
                }
                final GsmCellLocation location = (GsmCellLocation) telephony.getCellLocation();
                if (location != null) {
                    TextView cid = (TextView) findViewById(R.id.cid);
                    cid.setText("ECI: " + location.getCid());
                }
            }
            if (!TextUtils.isEmpty(networkOp)) {
                int mcc = Integer.parseInt(networkOp.substring(0, 3));
                int mnc = Integer.parseInt(networkOp.substring(3));
                TextView mncc = (TextView) findViewById(R.id.mnc);
                mncc.setText("MNC:" + mnc);
                TextView mccc = (TextView) findViewById(R.id.mcc);
                mccc.setText("MCC:" + mcc);

            }
        } else if (telephony.getNetworkType() == TelephonyManager.NETWORK_TYPE_UNKNOWN) {

            telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != 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.
                //        Toast.makeText(getBaseContext(), "If Clause :04",
                //              Toast.LENGTH_SHORT).show();
                return;
            }
            Log.i(TAG, "onCreate: 06 ");
            TelephonyManager tela = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String networkOp = tela.getNetworkOperator();
            CellInfoWcdma cellInfoWcdma = (CellInfoWcdma) telephonyManager.getAllCellInfo().get(0);
            CellSignalStrengthWcdma cellSignalStrengthWcdma = cellInfoWcdma.getCellSignalStrength();
            int rscp1 = cellSignalStrengthWcdma.getDbm();
            TextView rsp = (TextView) findViewById(R.id.rscp);
            rsp.setText("RSCP:" + rscp1 + "dbm");
            int asul = cellSignalStrengthWcdma.getAsuLevel();
            TextView asu = (TextView) findViewById(R.id.asu);
            asu.setText("ASU Level: " + asul);
            CellIdentityWcdma cellIdentityWcdma = cellInfoWcdma.getCellIdentity();
            int psc = cellIdentityWcdma.getPsc();
            TextView psci = (TextView) findViewById(R.id.pci);
            psci.setText("PSC: " + psc);
            int lac = cellIdentityWcdma.getLac();
            TextView lacc = (TextView) findViewById(R.id.lac);
            lacc.setText("LAC: " + lac);
            int cid = cellIdentityWcdma.getCid();
            TextView cidd = (TextView) findViewById(R.id.cid);
            cidd.setText("UCID: " + cid);
            TextView tech = (TextView) findViewById(R.id.tech);
            tech.setText("Technology: 3G");

            if (!TextUtils.isEmpty(networkOp)) {
                int mcc = Integer.parseInt(networkOp.substring(0, 3));
                int mnc = Integer.parseInt(networkOp.substring(3));
                TextView mncc = (TextView) findViewById(R.id.mnc);
                mncc.setText("MNC:" + mnc);
                TextView mccc = (TextView) findViewById(R.id.mcc);
                mccc.setText("MCC:" + mcc);
            }
        }
        else if (telephony.getNetworkType() == TelephonyManager.NETWORK_TYPE_EDGE) {
            telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != 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.
                //   Toast.makeText(getBaseContext(), "if Clause : 05",
                //         Toast.LENGTH_SHORT).show();
                return;
            }
            //  Log.i(TAG, "onCreate: 08 ");
            TelephonyManager teli = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String networkOp = teli.getNetworkOperator();
            CellInfoGsm cellinfogsm = (CellInfoGsm) telephonyManager.getAllCellInfo().get(0);
            CellSignalStrengthGsm cellSignalStrengthGsm = cellinfogsm.getCellSignalStrength();
            int ss = cellSignalStrengthGsm.getDbm();
            TextView sst = (TextView) findViewById(R.id.rssi);
            sst.setText("RSSI: " + ss + "dbm");
           /* int lev = cellSignalStrengthGsm.getLevel();
            TextView leve = (TextView) findViewById(R.id.levs);
            leve.setText("Rx Quality:" + lev); */
            int asul = cellSignalStrengthGsm.getAsuLevel();
            TextView asu = (TextView) findViewById(R.id.asu2g);
            asu.setText("ASU Level: " + asul);
            TextView tech = (TextView) findViewById(R.id.tech);
            tech.setText("Technology: 2G");
            //    Log.i(TAG, "onCreate: 08 ");

            if (!TextUtils.isEmpty(networkOp)) {
                int mcc = Integer.parseInt(networkOp.substring(0, 3));
                int mnc = Integer.parseInt(networkOp.substring(3));
                TextView mncc = (TextView) findViewById(R.id.mnc);
                mncc.setText("MNC:" + mnc);
                TextView mccc = (TextView) findViewById(R.id.mcc);
                mccc.setText("MCC:" + mcc);

            }
            if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {

                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != 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.
                    //        Toast.makeText(getBaseContext(), "If Clause : 06",
                    //              Toast.LENGTH_SHORT).show();
                    return;
                }
                final GsmCellLocation location = (GsmCellLocation) telephony.getCellLocation();
                if (location != null) {
                    TextView lac = (TextView) findViewById(R.id.lac);
                    lac.setText("LAC: " + location.getLac());
                    TextView cid = (TextView) findViewById(R.id.cid);
                    cid.setText("CID: " + location.getCid());
                }
            }
        }
            TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String networkOperator1 = tel.getNetworkOperator();


            String networkName = tel.getNetworkOperatorName();
            TextView name = (TextView) findViewById(R.id.name);
            name.setText("Operator: " + tel.getNetworkOperatorName());
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        0);
            }
            // Getting LocationManager object
            statusCheck();

            locationManager = (LocationManager) getSystemService(
                    Context.LOCATION_SERVICE);

            // Creating an empty criteria object
            Criteria criteria = new Criteria();

            // Getting the name of the provider that meets the criteria
            provider = locationManager.getBestProvider(criteria, false);

            if (provider != null && !provider.equals("")) {
                if (!provider.contains("gps")) { // if gps is disabled
                    final Intent poke = new Intent();
                    poke.setClassName("com.android.settings",
                            "com.android.settings.widget.SettingsAppWidgetProvider");
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse("3"));
                    sendBroadcast(poke);
                }
                // Get the location from the given provider
                Location location = locationManager
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 500, 0, this);

                if (location != null)
                    onLocationChanged(location);
                else
                    location = locationManager.getLastKnownLocation(provider);
                if (location != null)
                    onLocationChanged(location);
                else

                    Toast.makeText(getBaseContext(), "Location can't be retrieved",
                            Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(getBaseContext(), "No Provider Found",
                        Toast.LENGTH_SHORT).show();
            }
        }

    public void statusCheck() {
        final LocationManager manager = (LocationManager) getSystemService(
                Context.LOCATION_SERVICE);

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            buildAlertMessageNoGps();

        }
    }

    private void buildAlertMessageNoGps() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(
                "Your GPS seems to be disabled, do you want to enable it?")
                .setCancelable(false).setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog,
                                        final int id) {
                        startActivity(new Intent(
                                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog,
                                        final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        /* getMenuInflater().inflate(R.menu.activity_main, menu); */
        return true;
    }

    @Override
    public void onLocationChanged(Location location) {
        // Getting reference to TextView tv_longitude
        TextView tvLongitude = (TextView) findViewById(R.id.longi1);

        // Getting reference to TextView tv_latitude
        TextView tvLatitude = (TextView) findViewById(R.id.lati1);

        // Setting Current Longitude
        tvLongitude.setText("Longitude: " + location.getLongitude());

        // Setting Current Latitude
        tvLatitude.setText("Latitude: " + location.getLatitude());
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // Check Permissions Now
            ActivityCompat.requestPermissions(this,
                    new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    0);
        }
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}

1 个答案:

答案 0 :(得分:0)

因此,当您致电TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE)时,您需要检查instanceOf CellInfoLte。如果我关注您,那么您的类型转换CellInfoGsmCellInfoLte这是不可行的。现在您需要检查您的tm.getAllCellInfo()是否有您的对象然后执行您的任务。 以下代码用于理解: -

try {

    final TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    for (final CellInfo info : tm.getAllCellInfo()) {
        if (info instanceof CellInfoGsm) {
            final CellSignalStrengthGsm gsm = ((CellInfoGsm) info).getCellSignalStrength();
            // do what you need
        } else if (info instanceof CellInfoCdma) {
            final CellSignalStrengthCdma cdma = ((CellInfoCdma) info).getCellSignalStrength();
            // do what you need
        } else if (info instanceof CellInfoLte) {
            CellInfoLte cellInfoLte = (CellInfoLte) telephonyManager.getAllCellInfo().get(0);
            // do what you need
        } else {
            throw new Exception("Unknown type of cell signal!");
        }
    }
} catch (Exception e) {
    Log.e(TAG, "Unable to obtain cell signal information", e);
}