Brinda Tailor
Brinda Tailor

Reputation: 21

network parameters for dual sim in android studio

I am making an application that displays network parameters. When only one sim is active on my dual sim phone, the app works correctly and displays parameters of 2g, 3g or 4g respectively. But when both the sim cards are active the app crashes. How should I code to make the app work for both the sim cards and not get crashed? I am new to android studio and android coding.

edit [log]:

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)

edit [Code]:

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
    }
}

Upvotes: 1

Views: 1451

Answers (1)

duggu
duggu

Reputation: 38439

So when you call TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE) then you need to check instanceOf CellInfoLte. If see your crash then you got to know that you are casting CellInfoGsm to CellInfoLte (which is not doable). So , now you need to check tm.getAllCellInfo() having your object then do your task. Below code for understanding:-

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);
}

Upvotes: 2

Related Questions