List of usage examples for android.content Context TELEPHONY_SERVICE
String TELEPHONY_SERVICE
To view the source code for android.content Context TELEPHONY_SERVICE.
Click Source Link
From source file:com.geocine.mms.com.android.mms.transaction.HttpUtils.java
/** * A helper method to send or retrieve data through HTTP protocol. * * @param token The token to identify the sending progress. * @param url The URL used in a GET request. Null when the method is * HTTP_POST_METHOD.// ww w. j a v a 2 s . com * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD. * @param method HTTP_POST_METHOD or HTTP_GET_METHOD. * @return A byte array which contains the response data. * If an HTTP error code is returned, an IOException will be thrown. * @throws IOException if any error occurred on network interface or * an HTTP error code(>=400) returned from the server. */ protected static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method, boolean isProxySet, String proxyHost, int proxyPort) throws IOException { if (url == null) { throw new IllegalArgumentException("URL must not be null."); } if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.v(TAG, "httpConnection: params list"); Log.v(TAG, "\ttoken\t\t= " + token); Log.v(TAG, "\turl\t\t= " + url); Log.v(TAG, "\tmethod\t\t= " + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN"))); Log.v(TAG, "\tisProxySet\t= " + isProxySet); Log.v(TAG, "\tproxyHost\t= " + proxyHost); Log.v(TAG, "\tproxyPort\t= " + proxyPort); // TODO Print out binary data more readable. //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu)); } AndroidHttpClient client = null; try { // Make sure to use a proxy which supports CONNECT. URI hostUrl = new URI(url); HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME); client = createHttpClient(context); HttpRequest req = null; switch (method) { case HTTP_POST_METHOD: ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu); // Set request content type. entity.setContentType("application/vnd.wap.mms-message"); HttpPost post = new HttpPost(url); post.setEntity(entity); req = post; break; case HTTP_GET_METHOD: req = new HttpGet(url); break; default: Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD + "] or GET[" + HTTP_GET_METHOD + "]."); return null; } // Set route parameters for the request. HttpParams params = client.getParams(); if (isProxySet) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort)); } req.setParams(params); // Set necessary HTTP headers for MMS transmission. req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT); { String xWapProfileTagName = MmsConfig.getUaProfTagName(); String xWapProfileUrl = MmsConfig.getUaProfUrl(); if (xWapProfileUrl != null) { if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) { Log.d(LogTag.TRANSACTION, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl); } req.addHeader(xWapProfileTagName, xWapProfileUrl); } } // Extra http parameters. Split by '|' to get a list of value pairs. // Separate each pair by the first occurrence of ':' to obtain a name and // value. Replace the occurrence of the string returned by // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside // the value. String extraHttpParams = MmsConfig.getHttpParams(); if (extraHttpParams != null) { String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)) .getLine1Number(); String line1Key = MmsConfig.getHttpParamsLine1Key(); String paramList[] = extraHttpParams.split("\\|"); for (String paramPair : paramList) { String splitPair[] = paramPair.split(":", 2); if (splitPair.length == 2) { String name = splitPair[0].trim(); String value = splitPair[1].trim(); if (line1Key != null) { value = value.replace(line1Key, line1Number); } if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) { req.addHeader(name, value); } } } } req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE); HttpResponse response = client.execute(target, req); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { // HTTP 200 is success. throw new IOException("HTTP error: " + status.getReasonPhrase()); } HttpEntity entity = response.getEntity(); byte[] body = null; if (entity != null) { try { if (entity.getContentLength() > 0) { body = new byte[(int) entity.getContentLength()]; DataInputStream dis = new DataInputStream(entity.getContent()); try { dis.readFully(body); } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } if (entity.isChunked()) { Log.v(TAG, "httpConnection: transfer encoding is chunked"); int bytesTobeRead = MmsConfig.getMaxMessageSize(); byte[] tempBody = new byte[bytesTobeRead]; DataInputStream dis = new DataInputStream(entity.getContent()); try { int bytesRead = 0; int offset = 0; boolean readError = false; do { try { bytesRead = dis.read(tempBody, offset, bytesTobeRead); } catch (IOException e) { readError = true; Log.e(TAG, "httpConnection: error reading input stream" + e.getMessage()); break; } if (bytesRead > 0) { bytesTobeRead -= bytesRead; offset += bytesRead; } } while (bytesRead >= 0 && bytesTobeRead > 0); if (bytesRead == -1 && offset > 0 && !readError) { // offset is same as total number of bytes read // bytesRead will be -1 if the data was read till the eof body = new byte[offset]; System.arraycopy(tempBody, 0, body, 0, offset); Log.v(TAG, "httpConnection: Chunked response length [" + Integer.toString(offset) + "]"); } else { Log.e(TAG, "httpConnection: Response entity too large or empty"); } } finally { try { dis.close(); } catch (IOException e) { Log.e(TAG, "Error closing input stream: " + e.getMessage()); } } } } finally { if (entity != null) { entity.consumeContent(); } } } return body; } catch (URISyntaxException e) { handleHttpConnectionException(e, url); } catch (IllegalStateException e) { handleHttpConnectionException(e, url); } catch (IllegalArgumentException e) { handleHttpConnectionException(e, url); } catch (SocketException e) { handleHttpConnectionException(e, url); } catch (Exception e) { handleHttpConnectionException(e, url); } finally { if (client != null) { client.close(); } } return null; }
From source file:crow.util.Util.java
/** * ???? ?manifest ?? <uses-permission * android:name="android.permission.READ_PHONE_STATE"> * /*from w w w .j a v a 2s .com*/ * @param context * @return "" / "?" / "" / "" */ public static String getCarrier(Context context) { TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String imsi = telManager.getSubscriberId(); if (imsi != null && !"".equals(imsi)) { if (imsi.startsWith("46000") || imsi.startsWith("46002")) {// ?46000IMSI?46002?134/159?? return ""; } else if (imsi.startsWith("46001")) { return "?"; } else if (imsi.startsWith("46003")) { return ""; } } return ""; }
From source file:com.nextgis.firereporter.HttpGetter.java
static boolean IsNetworkAvailible(Context c) { ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info == null /*|| !cm.getBackgroundDataSetting()*/) return false; int netType = info.getType(); //int netSubtype = info.getSubtype(); if (netType == ConnectivityManager.TYPE_WIFI) { return info.isConnected(); } else if (netType == ConnectivityManager.TYPE_MOBILE && /*netSubtype == TelephonyManager.NETWORK_TYPE_UMTS &&*/ !tm.isNetworkRoaming()) { return info.isConnected(); } else {/*w w w . j av a 2 s.co m*/ return false; } }
From source file:com.wiyun.engine.network.Network.java
static int getNetworkType() { NetworkType type = NetworkType.NONE; if (isWifiConnected()) { type = NetworkType.WIFI;//from w w w. java2s . c o m } else { Context context = Director.getInstance().getContext(); TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (tm == null) type = NetworkType.NONE; else { int t = tm.getNetworkType(); if (t == TelephonyManager.NETWORK_TYPE_GPRS || t == TelephonyManager.NETWORK_TYPE_UNKNOWN) type = NetworkType.G2; else if (t == TelephonyManager.NETWORK_TYPE_EDGE) type = NetworkType.EDGE; else type = NetworkType.G3; } } return type.ordinal(); }
From source file:org.ubicompforall.BusTUC.Speech.HTTP.java
public DummyObj sendPost(String filePath, Context context, double lat, double lon) { String response = "Fant ikke noe"; long first = System.nanoTime(); Calc calc = new Calc(); DummyObj dummy = new DummyObj(); HttpClient httpclient = new DefaultHttpClient(); long second = System.nanoTime() - first; // File file = new File(Environment.getExternalStorageDirectory(), // filePath); File file = new File(filePath); HttpPost httppost = new HttpPost("http://vm-6114.idi.ntnu.no:1337/SpeechServer/sst"); final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String t_id = tm.getDeviceId(); String tmp = "TABuss"; String p_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); try {//from w ww . j av a 2 s . c o m MultipartEntity entity = new MultipartEntity(); entity.addPart("lat", new StringBody(String.valueOf(lat))); entity.addPart("lon", new StringBody(String.valueOf(lon))); entity.addPart("devID", new StringBody(tmp + p_id)); entity.addPart("speechinput", new FileBody(file, "multipart/form-data;charset=\"UTF-8\"")); httppost.setEntity(entity); response = EntityUtils.toString(httpclient.execute(httppost).getEntity(), "UTF-8"); System.out.println("RESPONSE: " + response); dummy = calc.parse(response); } catch (ClientProtocolException e) { } catch (IOException e) { } return dummy; }
From source file:com.ti.sensortag.gui.services.ServicesActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wakelockk = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock"); setContentView(R.layout.services_browser); //for checking signal strength.. MyListener = new MyPhoneStateListener(); Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); //ends../* w ww. ja v a2 s . c o m*/ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); test_1 = getIntent().getStringExtra("TEST"); Toast.makeText(getBaseContext(), "ARV in services SA :" + test_1, Toast.LENGTH_SHORT).show(); /* sendbutton = (Button) findViewById(R.id.button1); sendbutton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String sensorid = test_1; String sensortype = "temperature"; BufferedReader br = null; try { String sCurrentLine; File ext = Environment.getExternalStorageDirectory(); File myFile = new File(ext, "mysdfile_25.txt"); br = new BufferedReader(new FileReader(myFile)); while ((sCurrentLine = br.readLine()) != null) { String[] numberSplit = sCurrentLine.split(":") ; String time = numberSplit[ (numberSplit.length-2) ] ; String val = numberSplit[ (numberSplit.length-1) ] ; //System.out.println(sCurrentLine); HttpResponse httpresponse; //int responsecode; StatusLine responsecode; String strresp; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://rnicu-cloud.appspot.com/sensor/update"); try{ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("sensorid", sensorid)); nameValuePairs.add(new BasicNameValuePair("sensortype", sensortype)); nameValuePairs.add(new BasicNameValuePair("time", time)); nameValuePairs.add(new BasicNameValuePair("val", val)); // try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // try { httpresponse = httpclient.execute(httppost); //responsecode = httpresponse.getStatusLine().getStatusCode(); responsecode = httpresponse.getStatusLine(); strresp = responsecode.toString(); Log.d("ARV Response msg from post", httpresponse.toString()); Log.d("ARV status of post", strresp); HttpEntity httpentity = httpresponse.getEntity(); Log.d("ARV entity string", EntityUtils.toString(httpentity)); // Log.d("ARV oly entity", httpentity.toString()); // Log.d("ARV Entity response", httpentity.getContent().toString()); //httpclient.execute(httppost); Toast.makeText(getApplicationContext(), "Posted data and returned value:"+ strresp, Toast.LENGTH_LONG).show(); // } catch (ClientProtocolException e) { // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); // } // } }catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } // Toast.makeText(getApplicationContext(), "Entered on click", Toast.LENGTH_SHORT).show(); /*catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } });*/ getActionBar().setDisplayHomeAsUpEnabled(true); }
From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java
public Map<String, String> collectPrivateData() { Map<String, String> data = new HashMap<String, String>(); final TelephonyManager tm = (TelephonyManager) MyApp.context.getSystemService(Context.TELEPHONY_SERVICE); // final String androidId = Secure.getString( // MyApp.context.getContentResolver(), Secure.ANDROID_ID); // data.put("AndroidId", androidId); // data.put("Line1Number", tm.getLine1Number()); // data.put("CellLocation", tm.getCellLocation().toString()); // data.put("SimSerialNumber", tm.getSimSerialNumber()); // data.put("SimOperatorName", tm.getNetworkOperatorName()); // data.put("SubscriberId", tm.getSubscriberId()); data.put("DeviceId", tm.getDeviceId()); // data.put("Microphone", getMicrophoneSample()); // data.put("Camera", getCameraSample()); // data.put("Accelerometer", getAccelerometerSample()); return data;// w ww . ja v a 2 s .c o m }
From source file:com.example.hbranciforte.trafficclient.DataTraffic.java
private JSONObject getDeviceinfo() { JSONObject device = new JSONObject(); try {//w w w . j a v a2s . c o m TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String token = telephonyManager.getDeviceId().toString(); device.put("notification_token", token); device.put("user_agent", System.getProperty("http.agent").toString()); } catch (JSONException e) { Log.e("Json error", e.getMessage()); } return device; }
From source file:foo.fruitfox.evend.LoginActivity.java
private String getPhoneNumber() { String countryCode = ""; TelephonyManager tMgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); String mRawPhoneNumber = tMgr.getLine1Number(); String countryISO = tMgr.getSimCountryIso().toUpperCase(Locale.ENGLISH); String[] countryCodeList = this.getResources().getStringArray(R.array.CountryCodes); String mPhoneNumber;//w w w. j ava 2 s . c o m if (mRawPhoneNumber.startsWith("+") == false) { for (int i = 0; i < countryCodeList.length; i++) { String[] countryCodePair = countryCodeList[i].split(","); if (countryCodePair[1].trim().equals(countryISO.trim())) { countryCode = countryCodePair[0]; break; } } mPhoneNumber = "+" + countryCode + mRawPhoneNumber; } else { mPhoneNumber = mRawPhoneNumber; } return mPhoneNumber; }
From source file:com.wirelessmoves.cl.MainActivity.java
@SuppressWarnings("deprecation") @Override// ww w .j a v a 2 s. c o m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* If saved variable state exists from last run, recover it */ if (savedInstanceState != null) { NumberOfSignalStrengthUpdates = savedInstanceState.getLong("NumberOfSignalStrengthUpdates"); LastCellId = savedInstanceState.getLong("LastCellId"); NumberOfCellChanges = savedInstanceState.getLong("NumberOfCellChanges"); LastLacId = savedInstanceState.getLong("LastLacId"); NumberOfLacChanges = savedInstanceState.getLong("NumberOfLacChanges"); PreviousCells = savedInstanceState.getLongArray("PreviousCells"); PreviousCellsIndex = savedInstanceState.getInt("PreviousCellsIndex"); NumberOfUniqueCellChanges = savedInstanceState.getLong("NumberOfUniqueCellChanges"); outputDebugInfo = savedInstanceState.getBoolean("outputDebugInfo"); CurrentLocationLong = savedInstanceState.getDouble("CurrentLocationLong"); CurrentLocationLat = savedInstanceState.getDouble("CurrentLocationLat"); /* attempt to restore the previous gps location information object */ PrevLocation = (Location) getLastNonConfigurationInstance(); } else { /* Initialize PreviousCells Array to defined values */ for (int x = 0; x < PreviousCells.length; x++) PreviousCells[x] = 0; } /* Get a handle to the telephony manager service */ /* A listener will be installed in the object from the onResume() method */ MyListener = new MyPhoneStateListener(); Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); /* get a handle to the power manager and set a wake lock so the screen saver * is not activated after a timeout */ PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen"); /* Get a handle to the location system for getting GPS information */ locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); gpsListener = new myLocationListener(); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsListener); }