Example usage for android.content Context TELEPHONY_SERVICE

List of usage examples for android.content Context TELEPHONY_SERVICE

Introduction

In this page you can find the example usage for android.content Context TELEPHONY_SERVICE.

Prototype

String TELEPHONY_SERVICE

To view the source code for android.content Context TELEPHONY_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.telephony.TelephonyManager for handling management the telephony features of the device.

Usage

From source file:org.lumicall.android.sip.RegisterAccount.java

private String getMyPhoneNumber() {
    TelephonyManager mTelephonyMgr;/*from  w w  w  .  j  a  va2 s. c  om*/
    mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String num = mTelephonyMgr.getLine1Number();

    // MSISDN should not have a +, but some phones return it with a +
    // We want to see a +
    if (num != null && num.length() > 0 && !(num.charAt(0) == '+'))
        num = "+" + num;

    /* if(num == null || num.length() == 0) {
       PhoneHelper ph = new PhoneHelper();
       ph.init(this);
       num = ph.getLine1Number();
    } */

    if (num == null || num.length() == 0)
        num = "+" + getCountryCode(mTelephonyMgr.getSimCountryIso());

    return num;
}

From source file:de.ub0r.android.lib.DonationHelper.java

/**
 * Get MD5 hash of the IMEI (device id).
 * //from   w  ww  .j av a  2 s.  com
 * @param context
 *            {@link Context}
 * @return MD5 hash of IMEI
 */
public static String getImeiHash(final Context context) {
    if (imeiHash == null) {
        // get imei
        TelephonyManager mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String did = mTelephonyMgr.getDeviceId();
        if (did != null) {
            imeiHash = Utils.md5(did);
        } else {
            imeiHash = Utils.md5(Build.BOARD + Build.BRAND + Build.PRODUCT + Build.DEVICE);
        }
    }
    return imeiHash;
}

From source file:org.openremote.android.console.model.PollingHelper.java

/**
 * Read the device id for send it in polling request url.
 * /*from w ww .  ja  v a  2 s . co m*/
 * @param context the context
 */
private static void readDeviceId(Context context) {
    if (deviceId == null) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (IPAutoDiscoveryClient.isNetworkTypeWIFI) {
            deviceId = tm.getDeviceId();
        } else {
            deviceId = UUID.randomUUID().toString();
        }
    }
}

From source file:org.metawatch.manager.Monitors.java

public static void start(Context context, TelephonyManager telephonyManager) {
    // start weather updater

    if (Preferences.logging)
        Log.d(MetaWatch.TAG, "Monitors.start()");

    createBatteryLevelReciever(context);
    createWifiReceiver(context);//from  ww w. j  a  va2s  . co  m

    if (Preferences.weatherGeolocation) {
        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Initialising Geolocation");

        try {
            locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            locationProvider = LocationManager.NETWORK_PROVIDER;

            networkLocationListener = new NetworkLocationListener(context);

            locationManager.requestLocationUpdates(locationProvider, 30 * 60 * 1000, 500,
                    networkLocationListener);

            RefreshLocation();
        } catch (IllegalArgumentException e) {
            if (Preferences.logging)
                Log.d(MetaWatch.TAG, "Failed to initialise Geolocation " + e.getMessage());
        }
    } else {
        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Geolocation disabled");
    }

    CallStateListener phoneListener = new CallStateListener(context);

    telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    int phoneEvents = PhoneStateListener.LISTEN_CALL_STATE | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS
            | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE;
    telephonyManager.listen(phoneListener, phoneEvents);

    if (Utils.isGmailAccessSupported(context)) {
        gmailMonitor = new GmailMonitor(context);
        gmailMonitor.startMonitor();
    }

    try {
        contentObserverMessages = new ContentObserverMessages(context);
        Uri uri = Uri.parse("content://mms-sms/conversations/");
        contentResolverMessages = context.getContentResolver();
        contentResolverMessages.registerContentObserver(uri, true, contentObserverMessages);
    } catch (Exception x) {
    }

    try {
        contentObserverCalls = new ContentObserverCalls(context);
        //Uri uri = Uri.parse("content://mms-sms/conversations/");
        contentResolverCalls = context.getContentResolver();
        contentResolverCalls.registerContentObserver(android.provider.CallLog.Calls.CONTENT_URI, true,
                contentObserverCalls);
    } catch (Exception x) {
    }

    try {
        contentObserverAppointments = new ContentObserverAppointments(context);
        Uri uri = Uri.parse("content://com.android.calendar/calendars/");
        contentResolverAppointments = context.getContentResolver();
        contentResolverAppointments.registerContentObserver(uri, true, contentObserverAppointments);
    } catch (Exception x) {
    }

    // temporary one time update
    updateWeatherData(context);

    startAlarmTicker(context);
}

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));
    }// w ww  .ja  v  a2  s.  c  o m
    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.appnexus.opensdk.AdRequest.java

private AdRequest(AdRequester adRequester, int httpRetriesLeft, int blankRetriesLeft) {
    owner = adRequester.getOwner();/* w  w w. j  a  v a  2  s .  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.p2p.misc.DeviceUtility.java

public DeviceUtility(Context context) {
    mactivity = context;//from  w  ww .  j a v a  2 s  . co  m

    level = -1;
    telephonyManager = (TelephonyManager) mactivity.getSystemService(Context.TELEPHONY_SERVICE);

    try {
        cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
    } catch (Exception e) {
        e.printStackTrace();
    }

    Listener = new MyPhoneStateListener();
    //   batteryLevel();
    getSignalStrength();
}

From source file:com.wbtech.common.CommonUtil.java

/**
 * ??/*from ww w.j  a  v a2  s.  co m*/
 * @throws Exception
 */
public static SCell getCellInfo(Context context) throws Exception {
    SCell cell = new SCell();
    /** API?? */
    TelephonyManager mTelNet = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    GsmCellLocation location = (GsmCellLocation) mTelNet.getCellLocation();
    if (location == null) {
        if (UmsConstants.DebugMode) {
            Log.e("GsmCellLocation Error", "GsmCellLocation is null");
        }
        return null;
    }

    String operator = mTelNet.getNetworkOperator();
    //        System.out.println("operator------>"+operator.toString());
    int mcc = Integer.parseInt(operator.substring(0, 3));
    int mnc = Integer.parseInt(operator.substring(3));
    int cid = location.getCid();
    int lac = location.getLac();

    /** ? */
    cell.MCC = mcc;
    cell.MCCMNC = Integer.parseInt(operator);
    cell.MNC = mnc;
    cell.LAC = lac;
    cell.CID = cid;

    return cell;
}

From source file:com.netdoers.utils.ApplicationLoader.java

private void sendRegistrationIdToBackend() {
    TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String currentSIMImsi = mTelephonyMgr.getDeviceId();

    JSONObject jsonObject = getPushNotificationData(currentSIMImsi);
    Log.e("PUSH REGID SERVER---->>>>>>>>>>", jsonObject.toString());
    SendToServerTask sendTask = new SendToServerTask();
    sendTask.execute(new JSONObject[] { jsonObject });
}

From source file:com.silentcircle.silenttext.util.DeviceUtils.java

public static String getDeviceID(Context context) {
    TelephonyManager telephony = context != null
            ? (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)
            : null;//from w w  w.j  a  v  a  2  s. co m
    return telephony != null ? telephony.getDeviceId() : UUID.randomUUID().toString();
}