Example usage for android.telephony TelephonyManager getSimOperatorName

List of usage examples for android.telephony TelephonyManager getSimOperatorName

Introduction

In this page you can find the example usage for android.telephony TelephonyManager getSimOperatorName.

Prototype

public String getSimOperatorName() 

Source Link

Document

Returns the Service Provider Name (SPN).

Usage

From source file:com.master.metehan.filtereagle.Util.java

public static String getGeneralInfo(Context context) {
    StringBuilder sb = new StringBuilder();
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    sb.append(String.format("Interactive %B\r\n", isInteractive(context)));
    sb.append(String.format("Connected %B\r\n", isConnected(context)));
    sb.append(String.format("WiFi %B\r\n", isWifiActive(context)));
    sb.append(String.format("Metered %B\r\n", isMeteredNetwork(context)));
    sb.append(String.format("Roaming %B\r\n", isRoaming(context)));

    sb.append(String.format("Type %s\r\n", getPhoneTypeName(tm.getPhoneType())));

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1 || !hasPhoneStatePermission(context)) {
        if (tm.getSimState() == TelephonyManager.SIM_STATE_READY)
            sb.append(String.format("SIM %s/%s/%s\r\n", tm.getSimCountryIso(), tm.getSimOperatorName(),
                    tm.getSimOperator()));
        if (tm.getNetworkType() != TelephonyManager.NETWORK_TYPE_UNKNOWN)
            sb.append(String.format("Network %s/%s/%s\r\n", tm.getNetworkCountryIso(),
                    tm.getNetworkOperatorName(), tm.getNetworkOperator()));
    }/*from   ww  w  . j  a  v  a  2 s.  com*/

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        sb.append(String.format("Power saving %B\r\n", pm.isPowerSaveMode()));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        sb.append(String.format("Battery optimizing %B\r\n",
                !pm.isIgnoringBatteryOptimizations(context.getPackageName())));

    if (sb.length() > 2)
        sb.setLength(sb.length() - 2);

    return sb.toString();
}

From source file:com.softcoil.ApnDefaults.java

/**
 * Get the default ApnParameters for the current carrier from the APN_PARAMETERS_MAP. This uses
 * a combination of SIM MCCMNC, SIM operator name, network MCCMNC, and network name to try to
 * determine the correct parameters to use.
 *
 * If there is no match and fallback is true the method will attempt to return a match on the
 * SIM MCCMNC only. This will help in many cases but will return incorrect parameters in others.
 *
 * @param context The current context.//from w ww  .java  2 s.  c om
 * @param fallBack Should we attempt to fallback on matching just the SIM MCCMNC if we don't
 *                 find a match for the full key?
 * @return The ApnParameters or null.
 */
public static ApnParameters getApnParameters(Context context, boolean fallBack) {
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    StringBuffer sb = new StringBuffer().append(tm.getSimOperator()).append('|').append(tm.getSimOperatorName())
            .append('|').append(tm.getNetworkOperator()).append('|').append(tm.getNetworkOperatorName());

    ApnParameters apnParameters = APN_PARAMETERS_MAP.get(sb.toString());

    //Fallback on old data if we don't have new full network keys yet.
    if (apnParameters == null && fallBack) {
        apnParameters = APN_PARAMETERS_MAP.get(tm.getSimOperator());
    }

    return apnParameters;
}

From source file:com.mobicage.rogerthat.registration.AbstractRegistrationActivity.java

public void registerDevice() {
    T.UI();//from  ww w .  j  av  a  2s.c o m
    final HttpClient httpClient = HTTPUtil.getHttpClient();
    final String email = mWizard.getEmail();
    final String tosAge = mWizard.getTOSAge();
    final String pushNotifcationsEnabled = mWizard.getPushNotificationEnabled();
    final String timestamp = "" + mWizard.getTimestamp();
    final String deviceId = mWizard.getDeviceId();
    final String registrationId = mWizard.getRegistrationId();
    // Make call to Rogerthat
    String message = getString(R.string.activating);
    final ProgressDialog progressDialog = UIUtils.showProgressDialog(mActivity, null, message, true, false);
    final SafeRunnable showErrorDialog = new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            T.UI();
            progressDialog.dismiss();
            UIUtils.showErrorPleaseRetryDialog(mActivity);
        }
    };

    runOnWorker(new SafeRunnable() {
        @Override
        protected void safeRun() throws Exception {
            T.REGISTRATION();
            String version = "3";
            String signature = SecurityUtils.sha256(version + " " + email + " " + timestamp + " " + deviceId
                    + " " + registrationId + " " + CloudConstants.REGISTRATION_MAIN_SIGNATURE);

            HttpPost httppost = HTTPUtil.getHttpPost(mActivity,
                    CloudConstants.REGISTRATION_REGISTER_DEVICE_URL);
            try {
                List<NameValuePair> nameValuePairs = HTTPUtil.getRegistrationFormParams(mActivity);
                nameValuePairs.add(new BasicNameValuePair("version", version));
                nameValuePairs.add(new BasicNameValuePair("registration_time", timestamp));
                nameValuePairs.add(new BasicNameValuePair("device_id", deviceId));
                nameValuePairs.add(new BasicNameValuePair("registration_id", registrationId));
                nameValuePairs.add(new BasicNameValuePair("signature", signature));
                nameValuePairs.add(new BasicNameValuePair("email", email));
                nameValuePairs.add(new BasicNameValuePair("tos_age", tosAge));
                nameValuePairs
                        .add(new BasicNameValuePair("push_notifications_enabled", pushNotifcationsEnabled));
                nameValuePairs.add(new BasicNameValuePair("GCM_registration_id", getGCMRegistrationId()));
                nameValuePairs.add(new BasicNameValuePair("hardware_model", SystemPlugin.getDeviceModelName()));
                TelephonyManager telephonyManager = (TelephonyManager) mService
                        .getSystemService(Context.TELEPHONY_SERVICE);
                if (telephonyManager != null) {
                    nameValuePairs.add(
                            new BasicNameValuePair("sim_carrier_name", telephonyManager.getSimOperatorName()));
                }

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpClient.execute(httppost);

                int statusCode = response.getStatusLine().getStatusCode();
                HttpEntity entity = response.getEntity();

                if (entity == null) {
                    runOnUI(showErrorDialog);
                    return;
                }

                @SuppressWarnings("unchecked")
                final Map<String, Object> responseMap = (Map<String, Object>) JSONValue
                        .parse(new InputStreamReader(entity.getContent()));

                if (statusCode != 200 || responseMap == null) {
                    if (statusCode == 500 && responseMap != null) {
                        final String errorMessage = (String) responseMap.get("error");
                        if (errorMessage != null) {
                            runOnUI(new SafeRunnable() {
                                @Override
                                protected void safeRun() throws Exception {
                                    T.UI();
                                    progressDialog.dismiss();
                                    UIUtils.showDialog(mActivity, null, errorMessage);
                                }
                            });
                            return;
                        }
                    }
                    runOnUI(showErrorDialog);
                    return;
                }
                JSONObject account = (JSONObject) responseMap.get("account");
                setAgeAndGenderSet((Boolean) responseMap.get("age_and_gender_set"));

                final RegistrationInfo info = new RegistrationInfo(email,
                        new Credentials((String) account.get("account"), (String) account.get("password")));
                runOnUI(new SafeRunnable() {
                    @Override
                    protected void safeRun() throws Exception {
                        T.UI();
                        mWizard.setEmail(email);
                        mWizard.save();
                        tryConnect(progressDialog, 1, getString(R.string.registration_establish_connection,
                                email, getString(R.string.app_name)) + " ", info);
                    }
                });

            } catch (Exception e) {
                L.d(e);
                runOnUI(showErrorDialog);
            }
        }
    });
}

From source file:com.softcoil.ApnDefaults.java

/**
 * This method provides a means for clients to report new, good APN connection parameters
 * to a central repository so that they can be integrated with this class and shared with
 * the public.//  ww w  . j  a  v  a  2  s .co  m
 *
 * It contains protections so that new ApnParameters are only reported to the server the first
 * time this method is called. In addition, it uses a short connection timeout so it can be
 * safely called from your current worker thread without worry that it will unnecessarily
 * delay your process.
 *
 * It should be called immediately after successfully sending a MMS message. Example:<br/>
 *  <pre>
 *  //Send your MMS using whatever method you currently use.
 *  byte[] response = myMmsHttpPost(mmscUrl, mmsProxy, mmsProxyPort, sendReqPdu);
 *
 *  //Parse the response.
 *  SendConf sendConf = (SendConf) new PduParser(response).parse();
 *
 *  //Check to see if the response was success.
 *  if(sendConf != null && sendConf.getResponseStatus() == PduHeaders.RESPONSE_STATUS_OK) {
 *      //Report the ApnParameters used for the post.
 *      ApnParameters parameters = new ApnParameters(mmscUrl, mmsProxy, mmsProxyPort);
 *      ApnDefaults.reportApnData(context, parameters);
 *  }
 *
 *  //Continue your process.
 *  ...
 *  </pre>
 *
 *  In order for this class to be useful we must collect data from as many working
 *  configurations as possible. Adding a call to this method after a successful MMSC operation
 *  in your app will help us all to provide a good MMS experience to our users.
 *
 * @param context The current context.
 * @param apnParameters The known good ApnParameters to report.
 */
public static void reportApnData(Context context, ApnParameters apnParameters) {

    if (apnParameters == null)
        return;

    String apnData = apnParameters.getMmscUrl() + "|" + apnParameters.getProxyAddress() + "|"
            + apnParameters.getProxyPort();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String previousApnData = prefs.getString(PREF_KEY_LAST_APN_REPORT, null);

    if (!apnData.equals(previousApnData)) {

        //Save new apn data
        prefs.edit().putString(PREF_KEY_LAST_APN_REPORT, apnData).apply();

        //Report new apn data
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String networkOperator = tm.getNetworkOperator();
        String networkOperatorName = tm.getNetworkOperatorName();
        String simOperator = tm.getSimOperator();
        String simOperatorName = tm.getSimOperatorName();

        //Create HttpClient
        AndroidHttpClient client = AndroidHttpClient.newInstance("ApnDefaults/0.1");
        HttpParams params = client.getParams();
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpConnectionParams.setConnectionTimeout(params, 1 * 1000); //Set timeout to wait for a connection.
        HttpConnectionParams.setSoTimeout(params, 1 * 1000); //Set timeout to wait for a response.
        try {
            StringBuffer uriString = new StringBuffer(REPORT_URL).append("?")
                    //Report the MMSC connection used.
                    .append("apnData=").append(URLEncoder.encode(apnData, "UTF-8"))
                    //SIM and Network data are reported to enable determining which
                    //parameters work under which circumstances.
                    .append("&simOperator=").append(URLEncoder.encode(simOperator, "UTF-8"))
                    .append("&simOperatorName=").append(URLEncoder.encode(simOperatorName, "UTF-8"))
                    .append("&simCountry=").append(URLEncoder.encode(tm.getSimCountryIso(), "UTF-8"))
                    .append("&networkOperator=").append(URLEncoder.encode(networkOperator, "UTF-8"))
                    .append("&networkOperatorName=").append(URLEncoder.encode(networkOperatorName, "UTF-8"))
                    .append("&networkCountry=").append(URLEncoder.encode(tm.getNetworkCountryIso(), "UTF-8"));

            URI uri = new URI(uriString.toString());

            //Send request
            client.execute(new HttpGet(uri));
            client.close();
        } catch (Exception e) {
        }
    }
}

From source file:ua.mkh.weather.MainActivity.java

private void top_bar() {
    /////TIME//from   w  ww  .  ja  v  a 2s  .  co  m

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    String currentDateandTime = sdf.format(new Date());
    textView14.setText(currentDateandTime);

    ////OPERATOR
    TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    textView7.setText(tManager.getSimOperatorName());
    if (textView7.getText().toString().length() == 0) {
        textView7.setText(R.string.no_sim);
        ImageView i = (ImageView) findViewById(R.id.imageView3);
        i.setVisibility(View.GONE);
    }

}

From source file:uk.bowdlerize.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {
    case R.id.action_add: {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // Get the layout inflater
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_url, null);

        final EditText urlET = (EditText) dialogView.findViewById(R.id.urlET);

        builder.setView(dialogView)/*from   w  w  w. j a va  2 s . c  o m*/
                .setPositiveButton(R.string.action_add, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        Bundle extras = new Bundle();
                        Intent receiveURLIntent = new Intent(MainActivity.this, CensorCensusService.class);

                        extras.putString("url", urlET.getText().toString());
                        extras.putString("hash", MD5(urlET.getText().toString()));
                        extras.putInt("urgency", 0);
                        extras.putBoolean("local", true);

                        //Add our extra info
                        if (getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE)
                                .getBoolean("sendISPMeta", true)) {
                            WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
                            TelephonyManager telephonyManager = ((TelephonyManager) getSystemService(
                                    Context.TELEPHONY_SERVICE));

                            if (wifiMgr.isWifiEnabled() && null != wifiInfo.getSSID()) {
                                LocalCache lc = null;
                                Pair<Boolean, String> seenBefore = null;
                                try {
                                    lc = new LocalCache(MainActivity.this);
                                    lc.open();
                                    seenBefore = lc.findSSID(wifiInfo.getSSID().replaceAll("\"", ""));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                if (null != lc)
                                    lc.close();

                                if (seenBefore.first) {
                                    extras.putString("isp", seenBefore.second);
                                } else {
                                    extras.putString("isp", "unknown");
                                }

                                try {
                                    extras.putString("sim", telephonyManager.getSimOperatorName());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                try {
                                    extras.putString("isp", telephonyManager.getNetworkOperatorName());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                try {
                                    extras.putString("sim", telephonyManager.getSimOperatorName());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                        receiveURLIntent.putExtras(extras);
                        startService(receiveURLIntent);
                        dialog.cancel();
                    }
                }).setNegativeButton(R.string.action_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        builder.show();
        return true;
    }
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.lewa.crazychapter11.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    //set to full screen
    // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);

    ///set to no title
    // requestWindowFeature(Window.FEATURE_NO_TITLE);
    // acionBar = getSupportActionBar();
    // acionBar = getActionBar();
    // acionBar.hide();

    // Window win = getWindow();
    //          win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //          win.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS  | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);  
    //          win.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);  
    // win.setStatusBarColor(Color.TRANSPARENT);  
    // win.setNavigationBarColor(Color.TRANSPARENT);

    /*/// ww w.j av a2 s  .c  o m
       win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
       win.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS  | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);  
       win.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN  | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION  | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);  
       win.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);  
       win.setStatusBarColor(Color.TRANSPARENT);  
       win.setNavigationBarColor(Color.TRANSPARENT);
    //*/

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    /* setTheme(R.style.CrazyTheme); */
    AddGameBtn();
    AddNoification();
    LookupContact();
    AddServiceBtn();
    broadcastMain();
    mediaPlayerMain();
    mediaRecordSoundMain();
    cameraMain();
    recordvideoMain();
    queMySql();
    TestFragment();
    justForTest();
    LoadJson();
    AddTestBtn();
    AddUsageStatsBtn();
    AddPeopleProvideBtn();
    getInput();

    ////just for test shutdown broadcast receiver
    IntentFilter mIntentFilter = new IntentFilter("android.intent.action.ACTION_SHUTDOWN");
    mIntentFilter.addAction("com.lewa.alarm.test");
    mIntentFilter.addAction("android.provider.Telephony.SECRET_CODE");
    mIntentFilter.addAction("android.intent.action.SCREEN_ON");
    mIntentFilter.addAction("android.intent.action.SCREEN_OFF");
    mShoutdown = new shutdownReceiver();
    registerReceiver(mShoutdown, mIntentFilter);
    ////test      

    preferences = getSharedPreferences("crazyit", MODE_WORLD_WRITEABLE | MODE_WORLD_READABLE);
    editor = preferences.edit();

    preferencestime = getSharedPreferences("RMS_Shutdown_time", MODE_WORLD_WRITEABLE | MODE_WORLD_READABLE);
    editortime = preferencestime.edit();

    SharedShutdownTimeRead();

    AddSharedPreBtn();

    etNum = (EditText) findViewById(R.id.etNum);

    // //
    int maxLength = 4;

    InputFilter[] fArray = new InputFilter[1];

    fArray[0] = new InputFilter.LengthFilter(maxLength);

    etNum.setFilters(fArray);
    // //

    calThread = new CalThread();
    calThread.start();

    Log.i("algerheMain", "MainActivity onCreate in!!");
    String page = getString(R.string.str_page, "345", "24");
    Log.i("algerheMain", "page=" + page);

    // /just for test here
    ComponentName comp = getIntent().getComponent();
    show_txt = (EditText) findViewById(R.id.show_txt);
    show_txt.setText(
            "??" + comp.getPackageName() + " \n ??" + comp.getClassName());

    ////MD5 check item
    ///1.IMEI
    TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    String szImei = TelephonyMgr.getDeviceId();
    String m_szSIMSerialNm = TelephonyMgr.getSimSerialNumber();
    CellLocation m_location = TelephonyMgr.getCellLocation();
    String m_Line1Number = TelephonyMgr.getLine1Number();
    String m_OperatorName = TelephonyMgr.getSimOperatorName();
    Log.i("algerheTelephonyMgr", "szImei=" + szImei);
    Log.i("algerheTelephonyMgr", "m_szSIMSerialNm=" + m_szSIMSerialNm);
    Log.i("algerheTelephonyMgr", "m_location=" + m_location);
    Log.i("algerheTelephonyMgr", "m_Line1Number=" + m_Line1Number);
    Log.i("algerheTelephonyMgr", "m_OperatorName=" + m_OperatorName);

    Log.i("algerheMain01", "szImei=" + szImei);
    Log.i("algerheMain01", "m_szSIMSerialNm=" + m_szSIMSerialNm);

    ///2.Pseudo-Unique ID
    String m_szDevIDShort = "35" + //we make this look like a valid IMEI 
            Build.BOARD.length() % 10 + Build.BRAND.length() % 10 + Build.CPU_ABI.length() % 10
            + Build.DEVICE.length() % 10 + Build.DISPLAY.length() % 10 + Build.HOST.length() % 10
            + Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 + Build.MODEL.length() % 10
            + Build.PRODUCT.length() % 10 + Build.TAGS.length() % 10 + Build.TYPE.length() % 10
            + Build.USER.length() % 10; //13 digits

    Log.i("algerheMain01", "m_szDevIDShort=" + m_szDevIDShort);

    ///3. Android ID
    String m_szAndroidID = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
    Log.i("algerheMain01", "m_szAndroidID=" + m_szAndroidID);

    ///4.WLAN MAC Address string
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    String m_szWLANMAC = "unknow_wifi_mac";
    if (wm != null && wm.getConnectionInfo() != null) {
        m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
    }

    Log.i("algerheMain01", "m_szWLANMAC=" + m_szWLANMAC);

    ///5.BT MAC Address string
    BluetoothAdapter m_BluetoothAdapter = null; // Local Bluetooth adapter      
    m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    String m_szBTMAC = m_BluetoothAdapter.getAddress();

    Log.i("algerheMain01", "m_szBTMAC=" + m_szBTMAC);

    ///6.sim serial number .getSimSerialNumber()

    // /

    ///reflect test   
    checkMethod();

    // */
    final Intent alarmIntent = new Intent();
    Log.i("algerheMain00", "isLewaRom=" + isLewaRom(this, alarmIntent));

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x4567) {
                String languageStr = null;
                String countryStr = null;

                Locale[] locList = Locale.getAvailableLocales();

                for (int i = 0; i < locList.length; i++) {
                    languageStr += locList[i].getLanguage();
                    countryStr += locList[i].getCountry();
                }
                // show_txt = (EditText) findViewById(R.id.show_txt);
                show_txt.setText("" + languageStr + " \n " + countryStr);
            } else if (msg.what == 0x2789) {
                Log.i("algerheAlarm", "send alarm message in time=" + System.currentTimeMillis() + "\n action="
                        + alarmIntent.getAction());

                // sendBroadcast(alarmIntent);
            }
        }
    };

    // String strApkPath = intent.getStringExtra("apkPath");
    //         String strCmd = "pm install -r " + strApkPath;
    //         try {
    //             Process install = Runtime.getRuntime().exec(strCmd);
    //             Log.d(TAG, "install = " + install + ", strCmd =" + strCmd);
    //         }catch (Exception ex){
    //             Log.d(TAG, ex.getMessage());
    //         }   
    // */
}