List of usage examples for android.telephony TelephonyManager getNetworkOperator
public String getNetworkOperator()
From source file:com.secupwn.aimsicd.ui.activities.MainActivity.java
private void downloadBtsDataIfApiKeyAvailable() { if (CellTracker.OCID_API_KEY != null && !CellTracker.OCID_API_KEY.equals("NA")) { Cell cell = new Cell(); TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String networkOperator = tm.getNetworkOperator(); if (networkOperator != null && !networkOperator.isEmpty()) { int mcc = Integer.parseInt(networkOperator.substring(0, 3)); cell.setMobileCountryCode(mcc); int mnc = Integer.parseInt(networkOperator.substring(3)); cell.setMobileNetworkCode(mnc); log.debug("CELL:: mobileCountryCode=" + mcc + " mobileNetworkCode=" + mnc); }// w ww. j a v a 2s .c o m GeoLocation loc = mAimsicdService.lastKnownLocation(); if (loc != null) { Helpers.msgLong(this, getString(R.string.contacting_opencellid_for_data)); cell.setLon(loc.getLongitudeInDegrees()); cell.setLat(loc.getLatitudeInDegrees()); Helpers.getOpenCellData(this, cell, RequestTask.DBE_DOWNLOAD_REQUEST, mAimsicdService); } else { Helpers.msgShort(this, getString(R.string.waiting_for_location)); // This uses the LocationServices to get CID/LAC/MNC/MCC to be used // for grabbing the BTS data from OCID, via their API. // CID Location Async Output Delegate Interface Implementation LocationServices.LocationAsync locationAsync = new LocationServices.LocationAsync(); locationAsync.delegate = this; locationAsync.execute(mAimsicdService.getCell().getCellId(), mAimsicdService.getCell().getLocationAreaCode(), mAimsicdService.getCell().getMobileNetworkCode(), mAimsicdService.getCell().getMobileCountryCode()); } } else { Helpers.sendMsg(this, getString(R.string.no_opencellid_key_detected)); } }
From source file:com.appnexus.opensdk.AdRequest.java
private AdRequest(AdRequester adRequester, int httpRetriesLeft, int blankRetriesLeft) { owner = adRequester.getOwner();// w w w . ja v a 2s .c o m this.requester = adRequester; this.httpRetriesLeft = httpRetriesLeft; this.blankRetriesLeft = blankRetriesLeft; this.placementId = owner.getPlacementID(); context = owner.getContext(); String aid = android.provider.Settings.Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); // Do we have access to location? if (context.checkCallingOrSelfPermission( "android.permission.ACCESS_FINE_LOCATION") == PackageManager.PERMISSION_GRANTED || context.checkCallingOrSelfPermission( "android.permission.ACCESS_COARSE_LOCATION") == PackageManager.PERMISSION_GRANTED) { // Get lat, long from any GPS information that might be currently // available LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Location lastLocation = lm.getLastKnownLocation(lm.getBestProvider(new Criteria(), false)); if (lastLocation != null) { lat = "" + lastLocation.getLatitude(); lon = "" + lastLocation.getLongitude(); locDataAge = "" + (System.currentTimeMillis() - lastLocation.getTime()); locDataPrecision = "" + lastLocation.getAccuracy(); } } else { Clog.w(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_location)); } // Do we have permission ACCESS_NETWORK_STATE? if (context.checkCallingOrSelfPermission( "android.permission.ACCESS_NETWORK_STATE") != PackageManager.PERMISSION_GRANTED) { Clog.e(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_network_state)); fail(); this.cancel(true); return; } // Get orientation, the current rotation of the device orientation = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? "h" : "v"; // Get hidmd5, hidsha1, the device ID hashed if (Settings.getSettings().hidmd5 == null) { Settings.getSettings().hidmd5 = HashingFunctions.md5(aid); } hidmd5 = Settings.getSettings().hidmd5; if (Settings.getSettings().hidsha1 == null) { Settings.getSettings().hidsha1 = HashingFunctions.sha1(aid); } hidsha1 = Settings.getSettings().hidsha1; // Get devMake, devModel, the Make and Model of the current device devMake = Settings.getSettings().deviceMake; devModel = Settings.getSettings().deviceModel; // Get carrier if (Settings.getSettings().carrierName == null) { Settings.getSettings().carrierName = ((TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE)).getNetworkOperatorName(); } carrier = Settings.getSettings().carrierName; // Get firstlaunch and convert it to a string firstlaunch = Settings.getSettings().first_launch; // Get ua, the user agent... ua = Settings.getSettings().ua; // Get wxh if (owner.isBanner()) { this.width = ((BannerAdView) owner).getAdWidth(); this.height = ((BannerAdView) owner).getAdHeight(); } maxHeight = owner.getContainerHeight(); maxWidth = owner.getContainerWidth(); if (Settings.getSettings().mcc == null || Settings.getSettings().mnc == null) { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String networkOperator = tm.getNetworkOperator(); if (networkOperator != null && networkOperator.length() >= 6) { Settings.getSettings().mcc = networkOperator.substring(0, 3); Settings.getSettings().mnc = networkOperator.substring(3); } } mcc = Settings.getSettings().mcc; mnc = Settings.getSettings().mnc; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); connection_type = wifi.isConnected() ? "wifi" : "wan"; dev_time = "" + System.currentTimeMillis(); if (owner instanceof InterstitialAdView) { // Make string for allowed_sizes allowedSizes = ""; ArrayList<Size> sizes = ((InterstitialAdView) owner).getAllowedSizes(); for (Size s : sizes) { allowedSizes += "" + s.width() + "x" + s.height(); // If not last size, add a comma if (sizes.indexOf(s) != sizes.size() - 1) allowedSizes += ","; } } nativeBrowser = owner.getOpensNativeBrowser() ? "1" : "0"; //Reserve price reserve = owner.getReserve(); if (reserve <= 0) { this.psa = owner.shouldServePSAs ? "1" : "0"; } else { this.psa = "0"; } age = owner.getAge(); if (owner.getGender() != null) { if (owner.getGender() == AdView.GENDER.MALE) { gender = "m"; } else if (owner.getGender() == AdView.GENDER.FEMALE) { gender = "f"; } else { gender = null; } } customKeywords = owner.getCustomKeywords(); mcc = Settings.getSettings().mcc; mnc = Settings.getSettings().mnc; language = Settings.getSettings().language; }
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./*from www. j a v a 2s. com*/ * * 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:android_network.hetnet.vpn_service.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))); if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) sb.append(String.format("SIM %s/%s/%s\r\n", tm.getSimCountryIso(), tm.getSimOperatorName(), tm.getSimOperator()));/*from ww w. j av a 2s .c om*/ if (tm.getNetworkType() != TelephonyManager.NETWORK_TYPE_UNKNOWN) sb.append(String.format("Network %s/%s/%s\r\n", tm.getNetworkCountryIso(), tm.getNetworkOperatorName(), tm.getNetworkOperator())); 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", batteryOptimizing(context))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) sb.append(String.format("Data saving %B\r\n", dataSaving(context))); if (sb.length() > 2) sb.setLength(sb.length() - 2); return sb.toString(); }
From source file:com.google.android.gms.location.sample.geofencing.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); startService(new Intent(this, GsmService.class)); MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); GeoFenceApp.getLocationUtilityInstance().initialize(this); dataSource = GeoFenceApp.getInstance().getDataSource(); TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String networkOperator = tel.getNetworkOperator(); int mcc = 0, mnc = 0; if (networkOperator != null) { mcc = Integer.parseInt(networkOperator.substring(0, 3)); mnc = Integer.parseInt(networkOperator.substring(3)); }//ww w. ja v a 2 s .c om Log.i("", "mcc:" + mcc); Log.i("", "mnc:" + mnc); final AutoCompleteTextView autocompleteView = (AutoCompleteTextView) findViewById(R.id.autocomplete); mAdapter = new PlacesAutoCompleteAdapter(this, R.layout.text_adapter); autocompleteView.setAdapter(mAdapter); autocompleteView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Get data associated with the specified position // in the list (AdapterView) String description = (String) parent.getItemAtPosition(position); place = description; Toast.makeText(MainActivity.this, description, Toast.LENGTH_SHORT).show(); try { Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault()); List<Address> addresses = geocoder.getFromLocationName(description, 1); Address address = addresses.get(0); if (addresses.size() > 0) { autocompleteView.clearFocus(); //inputManager.hideSoftInputFromWindow(autocompleteView.getWindowToken(), 0); LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); Location location = new Location("Searched_Location"); location.setLatitude(latLng.latitude); location.setLongitude(latLng.longitude); setupMApIfNeeded(latLng); //setUpMapIfNeeded(location); //searchBar.setVisibility(View.GONE); //searchBtn.setVisibility(View.VISIBLE); } } catch (Exception e) { e.printStackTrace(); } } }); // Get the UI widgets. mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button); mRemoveGeofencesButton = (Button) findViewById(R.id.remove_geofences_button); // Empty list for storing geofences. mGeofenceList = new ArrayList<Geofence>(); // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null. mGeofencePendingIntent = null; // Retrieve an instance of the SharedPreferences object. mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, MODE_PRIVATE); // Get the value of mGeofencesAdded from SharedPreferences. Set to false as a default. mGeofencesAdded = mSharedPreferences.getBoolean(Constants.GEOFENCES_ADDED_KEY, false); setButtonsEnabledState(); // Get the geofences used. Geofence data is hard coded in this sample. populateGeofenceList(); // Kick off the request to build GoogleApiClient. buildGoogleApiClient(); autocompleteView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { final String value = s.toString(); // Remove all callbacks and messages mThreadHandler.removeCallbacksAndMessages(null); // Now add a new one mThreadHandler.postDelayed(new Runnable() { @Override public void run() { // Background thread mAdapter.resultList = mAdapter.mPlaceAPI.autocomplete(value); // Footer if (mAdapter.resultList.size() > 0) mAdapter.resultList.add("footer"); // Post to Main Thread mThreadHandler.sendEmptyMessage(1); } }, 500); } @Override public void afterTextChanged(Editable s) { //doAfterTextChanged(); } }); if (mThreadHandler == null) { // Initialize and start the HandlerThread // which is basically a Thread with a Looper // attached (hence a MessageQueue) mHandlerThread = new HandlerThread(TAG, android.os.Process.THREAD_PRIORITY_BACKGROUND); mHandlerThread.start(); // Initialize the Handler mThreadHandler = new Handler(mHandlerThread.getLooper()) { @Override public void handleMessage(Message msg) { if (msg.what == 1) { ArrayList<String> results = mAdapter.resultList; if (results != null && results.size() > 0) { runOnUiThread(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); //stuff that updates ui } }); } else { runOnUiThread(new Runnable() { @Override public void run() { //stuff that updates ui mAdapter.notifyDataSetInvalidated(); } }); } } } }; } GetID(); }
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 ww w . j av a 2 s . co m*/ * @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.yozio.android.YozioHelper.java
private void setCarrierMobileAndDeviceInfo() { SharedPreferences settings = context.getSharedPreferences("yozioPreferences", 0); try {//w ww .j av a 2 s. c o m TelephonyManager telephonyManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); carrierName = telephonyManager.getNetworkOperatorName(); carrierCountryCode = telephonyManager.getNetworkCountryIso(); if (telephonyManager.getNetworkOperator() != null && (telephonyManager.getNetworkOperator().length() == 5 || telephonyManager.getNetworkOperator().length() == 6)) { mobileCountryCode = telephonyManager.getNetworkOperator().substring(0, 3); mobileNetworkCode = telephonyManager.getNetworkOperator().substring(3); } deviceId = telephonyManager.getDeviceId(); if (!isValidDeviceId(deviceId)) { // Fetch the emulator device ID from the preferences deviceId = settings.getString("emulatorDeviceId", null); } if (!isValidDeviceId(deviceId)) { StringBuffer buff = new StringBuffer(); buff.append("emulator"); String chars = "1234567890abcdefghijklmnopqrstuvw"; int ccLength = chars.length() - 1; for (int i = 0; i < 32; i++) { int index = (int) (Math.random() * ccLength); buff.append(chars.charAt(index)); } SharedPreferences.Editor editor = settings.edit(); editor.putString("emulatorDeviceId", deviceId); editor.commit(); deviceId = buff.toString(); } deviceId = deviceId.toLowerCase(); } catch (Exception e) { deviceId = null; } }
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 w w w . j a v a 2 s . c o m 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.andybotting.tubechaser.activity.Home.java
/** * Upload statistics to remote server// w w w . j a va 2 s. com */ private void uploadStats() { if (LOGV) Log.v(TAG, "Sending statistics"); // gather all of the device info String app_version = ""; try { try { PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0); app_version = pi.versionName; } catch (NameNotFoundException e) { app_version = "N/A"; } TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String device_uuid = tm.getDeviceId(); String device_id = "00000000000000000000000000000000"; if (device_uuid != null) { device_id = GenericUtil.MD5(device_uuid); } String mobile_country_code = tm.getNetworkCountryIso(); String mobile_network_number = tm.getNetworkOperator(); int network_type = tm.getNetworkType(); // get the network type string String mobile_network_type = "N/A"; switch (network_type) { case 0: mobile_network_type = "TYPE_UNKNOWN"; break; case 1: mobile_network_type = "GPRS"; break; case 2: mobile_network_type = "EDGE"; break; case 3: mobile_network_type = "UMTS"; break; case 4: mobile_network_type = "CDMA"; break; case 5: mobile_network_type = "EVDO_0"; break; case 6: mobile_network_type = "EVDO_A"; break; case 7: mobile_network_type = "1xRTT"; break; case 8: mobile_network_type = "HSDPA"; break; case 9: mobile_network_type = "HSUPA"; break; case 10: mobile_network_type = "HSPA"; break; } String device_version = android.os.Build.VERSION.RELEASE; if (device_version == null) { device_version = "N/A"; } String device_model = android.os.Build.MODEL; if (device_model == null) { device_model = "N/A"; } String device_language = getResources().getConfiguration().locale.getLanguage(); String home_function = mPreferenceHelper.defaultLaunchActivity(); // post the data HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://tubechaser.andybotting.com/stats/app/send"); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("device_id", device_id)); pairs.add(new BasicNameValuePair("app_version", app_version)); pairs.add(new BasicNameValuePair("home_function", home_function)); pairs.add(new BasicNameValuePair("device_model", device_model)); pairs.add(new BasicNameValuePair("device_version", device_version)); pairs.add(new BasicNameValuePair("device_language", device_language)); pairs.add(new BasicNameValuePair("mobile_country_code", mobile_country_code)); pairs.add(new BasicNameValuePair("mobile_network_number", mobile_network_number)); pairs.add(new BasicNameValuePair("mobile_network_type", mobile_network_type)); try { post.setEntity(new UrlEncodedFormEntity(pairs)); } catch (UnsupportedEncodingException e) { // Do nothing } try { HttpResponse response = client.execute(post); response.getStatusLine().getStatusCode(); } catch (Exception e) { if (LOGV) Log.v(TAG, "Error uploading stats: " + e.getMessage()); } } catch (Exception e) { // Do nothing } }
From source file:fr.inria.ucn.collectors.NetworkStateCollector.java
@SuppressWarnings("deprecation") @SuppressLint("NewApi") private JSONObject getMobile(TelephonyManager tm) throws JSONException { JSONObject mob = new JSONObject(); mob.put("call_state", tm.getCallState()); mob.put("data_activity", tm.getDataActivity()); mob.put("network_type", tm.getNetworkType()); mob.put("network_type_str", Helpers.getTelephonyNetworkType(tm.getNetworkType())); mob.put("phone_type", tm.getPhoneType()); mob.put("phone_type_str", Helpers.getTelephonyPhoneType(tm.getPhoneType())); mob.put("sim_state", tm.getSimState()); mob.put("network_country", tm.getNetworkCountryIso()); mob.put("network_operator", tm.getNetworkOperator()); mob.put("network_operator_name", tm.getNetworkOperatorName()); // current cell location CellLocation cl = tm.getCellLocation(); if (cl != null) { JSONObject loc = new JSONObject(); if (cl instanceof GsmCellLocation) { JSONObject cell = new JSONObject(); cell.put("cid", ((GsmCellLocation) cl).getCid()); cell.put("lac", ((GsmCellLocation) cl).getLac()); cell.put("psc", ((GsmCellLocation) cl).getPsc()); loc.put("gsm", cell); } else if (cl instanceof CdmaCellLocation) { JSONObject cell = new JSONObject(); cell.put("bs_id", ((CdmaCellLocation) cl).getBaseStationId()); cell.put("bs_lat", ((CdmaCellLocation) cl).getBaseStationLatitude()); cell.put("bs_lon", ((CdmaCellLocation) cl).getBaseStationLongitude()); cell.put("net_id", ((CdmaCellLocation) cl).getNetworkId()); cell.put("sys_id", ((CdmaCellLocation) cl).getSystemId()); loc.put("cdma", cell); }// w ww .j av a 2 s . c om mob.put("cell_location", loc); } // Cell neighbors List<NeighboringCellInfo> ncl = tm.getNeighboringCellInfo(); if (ncl != null) { JSONArray cells = new JSONArray(); for (NeighboringCellInfo nc : ncl) { JSONObject jnc = new JSONObject(); jnc.put("cid", nc.getCid()); jnc.put("lac", nc.getLac()); jnc.put("network_type", nc.getNetworkType()); jnc.put("network_type_str", Helpers.getTelephonyNetworkType(nc.getNetworkType())); jnc.put("psc", nc.getPsc()); jnc.put("rssi", nc.getRssi()); cells.put(jnc); } mob.put("neigh_cells", cells); } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { // only works for API level >=17 List<CellInfo> aci = (List<CellInfo>) tm.getAllCellInfo(); if (aci != null) { JSONArray cells = new JSONArray(); for (CellInfo ci : aci) { JSONObject jci = new JSONObject(); if (ci instanceof CellInfoGsm) { CellInfoGsm cigsm = (CellInfoGsm) ci; jci.put("is_registered", cigsm.isRegistered()); jci.put("type", "gsm"); jci.put("cid", cigsm.getCellIdentity().getCid()); jci.put("lac", cigsm.getCellIdentity().getLac()); jci.put("mcc", cigsm.getCellIdentity().getMcc()); jci.put("mnc", cigsm.getCellIdentity().getMnc()); jci.put("psc", cigsm.getCellIdentity().getPsc()); jci.put("asu_level", cigsm.getCellSignalStrength().getAsuLevel()); jci.put("level", cigsm.getCellSignalStrength().getLevel()); jci.put("dbm", cigsm.getCellSignalStrength().getDbm()); } else if (ci instanceof CellInfoCdma) { CellInfoCdma cicdma = (CellInfoCdma) ci; jci.put("is_registered", cicdma.isRegistered()); jci.put("type", "cdma"); jci.put("bs_id", cicdma.getCellIdentity().getBasestationId()); jci.put("bs_lat", cicdma.getCellIdentity().getLatitude()); jci.put("bs_lon", cicdma.getCellIdentity().getLongitude()); jci.put("net_id", cicdma.getCellIdentity().getNetworkId()); jci.put("sys_id", cicdma.getCellIdentity().getSystemId()); jci.put("asu_level", cicdma.getCellSignalStrength().getAsuLevel()); jci.put("dbm", cicdma.getCellSignalStrength().getDbm()); jci.put("level", cicdma.getCellSignalStrength().getLevel()); jci.put("cdma_dbm", cicdma.getCellSignalStrength().getCdmaDbm()); jci.put("cdma_ecio", cicdma.getCellSignalStrength().getCdmaEcio()); jci.put("cdma_level", cicdma.getCellSignalStrength().getCdmaLevel()); jci.put("evdo_dbm", cicdma.getCellSignalStrength().getEvdoDbm()); jci.put("evdo_ecio", cicdma.getCellSignalStrength().getEvdoEcio()); jci.put("evdo_level", cicdma.getCellSignalStrength().getEvdoLevel()); jci.put("evdo_snr", cicdma.getCellSignalStrength().getEvdoSnr()); } else if (ci instanceof CellInfoWcdma) { CellInfoWcdma ciwcdma = (CellInfoWcdma) ci; jci.put("is_registered", ciwcdma.isRegistered()); jci.put("type", "wcdma"); jci.put("cid", ciwcdma.getCellIdentity().getCid()); jci.put("lac", ciwcdma.getCellIdentity().getLac()); jci.put("mcc", ciwcdma.getCellIdentity().getMcc()); jci.put("mnc", ciwcdma.getCellIdentity().getMnc()); jci.put("psc", ciwcdma.getCellIdentity().getPsc()); jci.put("asu_level", ciwcdma.getCellSignalStrength().getAsuLevel()); jci.put("dbm", ciwcdma.getCellSignalStrength().getDbm()); jci.put("level", ciwcdma.getCellSignalStrength().getLevel()); } else if (ci instanceof CellInfoLte) { CellInfoLte cilte = (CellInfoLte) ci; jci.put("is_registered", cilte.isRegistered()); jci.put("type", "lte"); jci.put("ci", cilte.getCellIdentity().getCi()); jci.put("mcc", cilte.getCellIdentity().getMcc()); jci.put("mnc", cilte.getCellIdentity().getMnc()); jci.put("pci", cilte.getCellIdentity().getPci()); jci.put("tac", cilte.getCellIdentity().getTac()); jci.put("asu_level", cilte.getCellSignalStrength().getAsuLevel()); jci.put("dbm", cilte.getCellSignalStrength().getDbm()); jci.put("level", cilte.getCellSignalStrength().getLevel()); jci.put("timing_adv", cilte.getCellSignalStrength().getTimingAdvance()); } cells.put(jci); } mob.put("all_cells", cells); } } return mob; }