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:hobby.wei.c.phone.Network.java

private static TelephonyManager getTelephonyManager(Context context) {
    return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
}

From source file:com.example.jumpnote.android.SyncAdapter.java

@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        final ContentProviderClient provider, final SyncResult syncResult) {
    TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    String clientDeviceId = tm.getDeviceId();

    final long newSyncTime = System.currentTimeMillis();

    final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
    final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);

    C2DMReceiver.refreshAppC2DMRegistrationState(mContext);

    Log.i(TAG, "Beginning " + (uploadOnly ? "upload-only" : "full") + " sync for account " + account.name);

    // Read this account's sync metadata
    final SharedPreferences syncMeta = mContext.getSharedPreferences("sync:" + account.name, 0);
    long lastSyncTime = syncMeta.getLong(LAST_SYNC, 0);
    long lastServerSyncTime = syncMeta.getLong(SERVER_LAST_SYNC, 0);

    // Check for changes in either app-wide auto sync registration information, or changes in
    // the user's preferences for auto sync on this account; if either changes, piggy back the
    // new registration information in this sync.
    long lastRegistrationChangeTime = C2DMessaging.getLastRegistrationChange(mContext);

    boolean autoSyncDesired = ContentResolver.getMasterSyncAutomatically()
            && ContentResolver.getSyncAutomatically(account, JumpNoteContract.AUTHORITY);
    boolean autoSyncEnabled = syncMeta.getBoolean(DM_REGISTERED, false);

    // Will be 0 for no change, -1 for unregister, 1 for register.
    final int deviceRegChange;
    JsonRpcClient.Call deviceRegCall = null;
    if (autoSyncDesired != autoSyncEnabled || lastRegistrationChangeTime > lastSyncTime || initialize
            || manualSync) {//from   w  w w . j av a  2s. c  o m

        String registrationId = C2DMessaging.getRegistrationId(mContext);
        deviceRegChange = (autoSyncDesired && registrationId != null) ? 1 : -1;

        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG,
                    "Auto sync selection or registration information has changed, "
                            + (deviceRegChange == 1 ? "registering" : "unregistering")
                            + " messaging for this device, for account " + account.name);
        }

        try {
            if (deviceRegChange == 1) {
                // Register device for auto sync on this account.
                deviceRegCall = new JsonRpcClient.Call(JumpNoteProtocol.DevicesRegister.METHOD);
                JSONObject params = new JSONObject();

                DeviceRegistration device = new DeviceRegistration(clientDeviceId, DEVICE_TYPE, registrationId);
                params.put(JumpNoteProtocol.DevicesRegister.ARG_DEVICE, device.toJSON());
                deviceRegCall.setParams(params);
            } else {
                // Unregister device for auto sync on this account.
                deviceRegCall = new JsonRpcClient.Call(JumpNoteProtocol.DevicesUnregister.METHOD);
                JSONObject params = new JSONObject();
                params.put(JumpNoteProtocol.DevicesUnregister.ARG_DEVICE_ID, clientDeviceId);
                deviceRegCall.setParams(params);
            }
        } catch (JSONException e) {
            logErrorMessage("Error generating device registration remote RPC parameters.", manualSync);
            e.printStackTrace();
            return;
        }
    } else {
        deviceRegChange = 0;
    }

    // Get the list of locally changed notes. If this is an upload-only sync and there were
    // no local changes, cancel the sync.
    List<ModelJava.Note> locallyChangedNotes = null;
    try {
        locallyChangedNotes = getLocallyChangedNotes(provider, account, new Date(lastSyncTime));
    } catch (RemoteException e) {
        logErrorMessage("Remote exception accessing content provider: " + e.getMessage(), manualSync);
        e.printStackTrace();
        syncResult.stats.numIoExceptions++;
        return;
    }

    if (uploadOnly && locallyChangedNotes.isEmpty() && deviceRegCall == null) {
        Log.i(TAG, "No local changes; upload-only sync canceled.");
        return;
    }

    // Set up the RPC sync calls
    final AuthenticatedJsonRpcJavaClient jsonRpcClient = new AuthenticatedJsonRpcJavaClient(mContext,
            Config.SERVER_AUTH_URL_TEMPLATE, Config.SERVER_RPC_URL);
    try {
        jsonRpcClient.blockingAuthenticateAccount(account,
                manualSync ? AuthenticatedJsonRpcJavaClient.NEED_AUTH_INTENT
                        : AuthenticatedJsonRpcJavaClient.NEED_AUTH_NOTIFICATION,
                false);
    } catch (AuthenticationException e) {
        logErrorMessage("Authentication exception when attempting to sync.", manualSync);
        e.printStackTrace();
        syncResult.stats.numAuthExceptions++;
        return;
    } catch (OperationCanceledException e) {
        Log.i(TAG, "Sync for account " + account.name + " manually canceled.");
        return;
    } catch (RequestedUserAuthenticationException e) {
        syncResult.stats.numAuthExceptions++;
        return;
    } catch (InvalidAuthTokenException e) {
        logErrorMessage("Invalid auth token provided by AccountManager when attempting to " + "sync.",
                manualSync);
        e.printStackTrace();
        syncResult.stats.numAuthExceptions++;
        return;
    }

    // Set up the notes sync call.
    JsonRpcClient.Call notesSyncCall = new JsonRpcClient.Call(JumpNoteProtocol.NotesSync.METHOD);
    try {
        JSONObject params = new JSONObject();
        params.put(JumpNoteProtocol.ARG_CLIENT_DEVICE_ID, clientDeviceId);
        params.put(JumpNoteProtocol.NotesSync.ARG_SINCE_DATE,
                Util.formatDateISO8601(new Date(lastServerSyncTime)));

        JSONArray locallyChangedNotesJson = new JSONArray();
        for (ModelJava.Note locallyChangedNote : locallyChangedNotes) {
            locallyChangedNotesJson.put(locallyChangedNote.toJSON());
        }

        params.put(JumpNoteProtocol.NotesSync.ARG_LOCAL_NOTES, locallyChangedNotesJson);
        notesSyncCall.setParams(params);
    } catch (JSONException e) {
        logErrorMessage("Error generating sync remote RPC parameters.", manualSync);
        e.printStackTrace();
        syncResult.stats.numParseExceptions++;
        return;
    }

    List<JsonRpcClient.Call> jsonRpcCalls = new ArrayList<JsonRpcClient.Call>();
    jsonRpcCalls.add(notesSyncCall);
    if (deviceRegChange != 0)
        jsonRpcCalls.add(deviceRegCall);

    jsonRpcClient.callBatch(jsonRpcCalls, new JsonRpcClient.BatchCallback() {
        public void onData(Object[] data) {
            if (data[0] != null) {
                // Read notes sync data.
                JSONObject dataJson = (JSONObject) data[0];
                try {
                    List<ModelJava.Note> changedNotes = new ArrayList<ModelJava.Note>();
                    JSONArray notesJson = dataJson.getJSONArray(JumpNoteProtocol.NotesSync.RET_NOTES);
                    for (int i = 0; i < notesJson.length(); i++) {
                        changedNotes.add(new ModelJava.Note(notesJson.getJSONObject(i)));
                    }

                    reconcileSyncedNotes(provider, account, changedNotes, syncResult.stats);

                    // If sync is successful (no exceptions thrown), update sync metadata
                    long newServerSyncTime = Util
                            .parseDateISO8601(dataJson.getString(JumpNoteProtocol.NotesSync.RET_NEW_SINCE_DATE))
                            .getTime();
                    syncMeta.edit().putLong(LAST_SYNC, newSyncTime).commit();
                    syncMeta.edit().putLong(SERVER_LAST_SYNC, newServerSyncTime).commit();
                    Log.i(TAG, "Sync complete, setting last sync time to " + Long.toString(newSyncTime));
                } catch (JSONException e) {
                    logErrorMessage("Error parsing note sync RPC response", manualSync);
                    e.printStackTrace();
                    syncResult.stats.numParseExceptions++;
                    return;
                } catch (ParseException e) {
                    logErrorMessage("Error parsing note sync RPC response", manualSync);
                    e.printStackTrace();
                    syncResult.stats.numParseExceptions++;
                    return;
                } catch (RemoteException e) {
                    logErrorMessage("RemoteException in reconcileSyncedNotes: " + e.getMessage(), manualSync);
                    e.printStackTrace();
                    return;
                } catch (OperationApplicationException e) {
                    logErrorMessage("Could not apply batch operations to content provider: " + e.getMessage(),
                            manualSync);
                    e.printStackTrace();
                    return;
                } finally {
                    provider.release();
                }
            }

            // Read device reg data.
            if (deviceRegChange != 0) {
                // data[1] will be null in case of an error (successful unregisters
                // will have an empty JSONObject, not null).
                boolean registered = (data[1] != null && deviceRegChange == 1);
                syncMeta.edit().putBoolean(DM_REGISTERED, registered).commit();
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Stored account auto sync registration state: " + Boolean.toString(registered));
                }
            }
        }

        public void onError(int callIndex, JsonRpcException e) {
            if (e.getHttpCode() == 403) {
                Log.w(TAG, "Got a 403 response, invalidating App Engine ACSID token");
                jsonRpcClient.invalidateAccountAcsidToken(account);
            }

            provider.release();
            logErrorMessage("Error calling remote note sync RPC", manualSync);
            e.printStackTrace();
        }
    });
}

From source file:com.samsung.android.remindme.SyncAdapter.java

@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        final ContentProviderClient provider, final SyncResult syncResult) {
    Log.i(TAG, "onPerformSync called!");
    TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    String clientDeviceId = tm.getDeviceId();

    final long newSyncTime = System.currentTimeMillis();

    final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
    final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);

    C2DMReceiver.refreshAppC2DMRegistrationState(mContext);

    Log.i(TAG, "Beginning " + (uploadOnly ? "upload-only" : "full") + " sync for account " + account.name);

    // Read this account's sync metadata
    final SharedPreferences syncMeta = mContext.getSharedPreferences("sync:" + account.name, 0);
    long lastSyncTime = syncMeta.getLong(LAST_SYNC, 0);
    long lastServerSyncTime = syncMeta.getLong(SERVER_LAST_SYNC, 0);

    // Check for changes in either app-wide auto sync registration information, or changes in
    // the user's preferences for auto sync on this account; if either changes, piggy back the
    // new registration information in this sync.
    long lastRegistrationChangeTime = C2DMessaging.getLastRegistrationChange(mContext);

    boolean autoSyncDesired = ContentResolver.getMasterSyncAutomatically()
            && ContentResolver.getSyncAutomatically(account, RemindMeContract.AUTHORITY);
    boolean autoSyncEnabled = syncMeta.getBoolean(DM_REGISTERED, false);

    // Will be 0 for no change, -1 for unregister, 1 for register.
    final int deviceRegChange;
    JsonRpcClient.Call deviceRegCall = null;
    if (autoSyncDesired != autoSyncEnabled || lastRegistrationChangeTime > lastSyncTime || initialize
            || manualSync) {/*from  ww w.  ja v  a  2  s  .com*/

        String registrationId = C2DMessaging.getRegistrationId(mContext);
        deviceRegChange = (autoSyncDesired && registrationId != null) ? 1 : -1;

        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG,
                    "Auto sync selection or registration information has changed, "
                            + (deviceRegChange == 1 ? "registering" : "unregistering")
                            + " messaging for this device, for account " + account.name);
        }

        try {
            if (deviceRegChange == 1) {
                // Register device for auto sync on this account.
                deviceRegCall = new JsonRpcClient.Call(RemindMeProtocol.DevicesRegister.METHOD);
                JSONObject params = new JSONObject();

                DeviceRegistration device = new DeviceRegistration(clientDeviceId, DEVICE_TYPE, registrationId);
                params.put(RemindMeProtocol.DevicesRegister.ARG_DEVICE, device.toJSON());
                deviceRegCall.setParams(params);
            } else {
                // Unregister device for auto sync on this account.
                deviceRegCall = new JsonRpcClient.Call(RemindMeProtocol.DevicesUnregister.METHOD);
                JSONObject params = new JSONObject();
                params.put(RemindMeProtocol.DevicesUnregister.ARG_DEVICE_ID, clientDeviceId);
                deviceRegCall.setParams(params);
            }
        } catch (JSONException e) {
            logErrorMessage("Error generating device registration remote RPC parameters.", manualSync);
            e.printStackTrace();
            return;
        }
    } else {
        deviceRegChange = 0;
    }

    // Get the list of locally changed alerts. If this is an upload-only sync and there were
    // no local changes, cancel the sync.
    List<ModelJava.Alert> locallyChangedAlerts = null;
    try {
        locallyChangedAlerts = getLocallyChangedAlerts(provider, account, new Date(lastSyncTime));
    } catch (RemoteException e) {
        logErrorMessage("Remote exception accessing content provider: " + e.getMessage(), manualSync);
        e.printStackTrace();
        syncResult.stats.numIoExceptions++;
        return;
    }

    if (uploadOnly && locallyChangedAlerts.isEmpty() && deviceRegCall == null) {
        Log.i(TAG, "No local changes; upload-only sync canceled.");
        return;
    }

    // Set up the RPC sync calls
    final AuthenticatedJsonRpcJavaClient jsonRpcClient = new AuthenticatedJsonRpcJavaClient(mContext,
            Config.SERVER_AUTH_URL_TEMPLATE, Config.SERVER_RPC_URL);
    try {
        jsonRpcClient.blockingAuthenticateAccount(account,
                manualSync ? AuthenticatedJsonRpcJavaClient.NEED_AUTH_INTENT
                        : AuthenticatedJsonRpcJavaClient.NEED_AUTH_NOTIFICATION,
                false);
    } catch (AuthenticationException e) {
        logErrorMessage("Authentication exception when attempting to sync. root cause: " + e.getMessage(),
                manualSync);
        e.printStackTrace();

        syncResult.stats.numAuthExceptions++;
        return;
    } catch (OperationCanceledException e) {
        Log.i(TAG, "Sync for account " + account.name + " manually canceled.");
        return;
    } catch (RequestedUserAuthenticationException e) {
        syncResult.stats.numAuthExceptions++;
        return;
    } catch (InvalidAuthTokenException e) {
        logErrorMessage("Invalid auth token provided by AccountManager when attempting to " + "sync.",
                manualSync);
        e.printStackTrace();
        syncResult.stats.numAuthExceptions++;
        return;
    }

    // Set up the alerts sync call.
    JsonRpcClient.Call alertsSyncCall = new JsonRpcClient.Call(RemindMeProtocol.AlertsSync.METHOD);
    try {
        JSONObject params = new JSONObject();
        params.put(RemindMeProtocol.ARG_CLIENT_DEVICE_ID, clientDeviceId);
        params.put(RemindMeProtocol.AlertsSync.ARG_SINCE_DATE,
                Util.formatDateISO8601(new Date(lastServerSyncTime)));

        JSONArray locallyChangedAlertsJson = new JSONArray();
        for (ModelJava.Alert locallyChangedAlert : locallyChangedAlerts) {
            locallyChangedAlertsJson.put(locallyChangedAlert.toJSON());
        }

        params.put(RemindMeProtocol.AlertsSync.ARG_LOCAL_NOTES, locallyChangedAlertsJson);
        alertsSyncCall.setParams(params);
    } catch (JSONException e) {
        logErrorMessage("Error generating sync remote RPC parameters.", manualSync);
        e.printStackTrace();
        syncResult.stats.numParseExceptions++;
        return;
    }

    List<JsonRpcClient.Call> jsonRpcCalls = new ArrayList<JsonRpcClient.Call>();
    jsonRpcCalls.add(alertsSyncCall);
    if (deviceRegChange != 0)
        jsonRpcCalls.add(deviceRegCall);

    jsonRpcClient.callBatch(jsonRpcCalls, new JsonRpcClient.BatchCallback() {
        public void onData(Object[] data) {
            if (data[0] != null) {
                // Read alerts sync data.
                JSONObject dataJson = (JSONObject) data[0];
                try {
                    List<ModelJava.Alert> changedAlerts = new ArrayList<ModelJava.Alert>();
                    JSONArray alertsJson = dataJson.getJSONArray(RemindMeProtocol.AlertsSync.RET_NOTES);
                    for (int i = 0; i < alertsJson.length(); i++) {
                        changedAlerts.add(new ModelJava.Alert(alertsJson.getJSONObject(i)));
                    }

                    reconcileSyncedAlerts(provider, account, changedAlerts, syncResult.stats);

                    // If sync is successful (no exceptions thrown), update sync metadata
                    long newServerSyncTime = Util
                            .parseDateISO8601(
                                    dataJson.getString(RemindMeProtocol.AlertsSync.RET_NEW_SINCE_DATE))
                            .getTime();
                    syncMeta.edit().putLong(LAST_SYNC, newSyncTime).commit();
                    syncMeta.edit().putLong(SERVER_LAST_SYNC, newServerSyncTime).commit();
                    Log.i(TAG, "Sync complete, setting last sync time to " + Long.toString(newSyncTime));
                } catch (JSONException e) {
                    logErrorMessage("Error parsing alert sync RPC response", manualSync);
                    e.printStackTrace();
                    syncResult.stats.numParseExceptions++;
                    return;
                } catch (ParseException e) {
                    logErrorMessage("Error parsing alert sync RPC response", manualSync);
                    e.printStackTrace();
                    syncResult.stats.numParseExceptions++;
                    return;
                } catch (RemoteException e) {
                    logErrorMessage("RemoteException in reconcileSyncedAlerts: " + e.getMessage(), manualSync);
                    e.printStackTrace();
                    return;
                } catch (OperationApplicationException e) {
                    logErrorMessage("Could not apply batch operations to content provider: " + e.getMessage(),
                            manualSync);
                    e.printStackTrace();
                    return;
                } finally {
                    provider.release();
                }
            }

            // Read device reg data.
            if (deviceRegChange != 0) {
                // data[1] will be null in case of an error (successful unregisters
                // will have an empty JSONObject, not null).
                boolean registered = (data[1] != null && deviceRegChange == 1);
                syncMeta.edit().putBoolean(DM_REGISTERED, registered).commit();
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "Stored account auto sync registration state: " + Boolean.toString(registered));
                }
            }
        }

        public void onError(int callIndex, JsonRpcException e) {
            if (e.getHttpCode() == 403) {
                Log.w(TAG, "Got a 403 response, invalidating App Engine ACSID token");
                jsonRpcClient.invalidateAccountAcsidToken(account);
            }

            provider.release();
            logErrorMessage("Error calling remote alert sync RPC", manualSync);
            e.printStackTrace();
        }
    });
}

From source file:com.toppatch.mv.ui.activities.LoginActivity2.java

@SuppressWarnings("unchecked")
private void startLoginCheck() {
    Log.d(TAG, "startLoginCheck");
    CheckLoginAsyncTask check = new CheckLoginAsyncTask();
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(Constants.LOGIN_ACTIVITY_EMAIL, email.getText().toString()));
    params.add(new BasicNameValuePair(Constants.LOGIN_ACTIVITY_PASSCODE, passcode.getText().toString()));
    params.add(new BasicNameValuePair(Constants.LOGIN_ACTIVITY_GCM, gcmId));
    TelephonyManager mngr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    params.add(new BasicNameValuePair(Constants.IMEI, mngr.getDeviceId()));
    Log.d("see", "sss:" + gcmId);
    check.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
}

From source file:com.pandoroid.PandoraRadioService.java

@Override
public void onCreate() {
    m_paused = false;//w  w  w  .  j  a  v a2 s  . co m
    m_pandora_remote = new PandoraRadio();
    image_downloader = new ImageDownloader();
    m_stations = new ArrayList<Station>();

    connectivity_manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    m_prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    // Register the listener with the telephony manager
    telephonyManager.listen(new PhoneStateListener() {
        boolean pausedForRing = false;

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {

            case TelephonyManager.CALL_STATE_IDLE:
                if (pausedForRing && m_song_playback != null) {
                    if (m_prefs.getBoolean("behave_resumeOnHangup", true)) {
                        if (m_song_playback != null && !m_paused) {
                            m_song_playback.play();
                        }
                    }
                }

                pausedForRing = false;
                break;

            case TelephonyManager.CALL_STATE_OFFHOOK:
            case TelephonyManager.CALL_STATE_RINGING:
                if (m_song_playback != null) {
                    m_song_playback.pause();
                }

                pausedForRing = true;
                break;
            }
        }
    }, PhoneStateListener.LISTEN_CALL_STATE);

    m_music_intent_receiver = new MusicIntentReceiver();
    this.registerReceiver(m_music_intent_receiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
}

From source file:org.hfoss.posit.web.Communicator.java

public Communicator(Context _context) {
    mContext = _context;// ww w  . jav  a 2 s.c  o m
    mTotalTime = 0;
    mStart = 0;

    mHttpParams = new BasicHttpParams();
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    mConnectionManager = new ThreadSafeClientConnManager(mHttpParams, registry);
    mHttpClient = new DefaultHttpClient(mConnectionManager, mHttpParams);

    PreferenceManager.setDefaultValues(mContext, R.xml.posit_preferences, false);
    applicationPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    setApplicationAttributes(applicationPreferences.getString("AUTHKEY", ""),
            applicationPreferences.getString("SERVER_ADDRESS", server),
            applicationPreferences.getInt("PROJECT_ID", projectId));
    TelephonyManager manager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    imei = manager.getDeviceId();

}

From source file:com.mcnc.parecis.bizmob.task.Login20Task.java

@Override
protected Response doInBackground(Object... arg0) {
    Response response = new Response();
    final Request request = getRequest();

    final BaseActivity activity = request.getSrcActivity();
    String callback = "";
    String legacy_trcode = "";

    JSONObject root = null;//from  w ww .  ja v a  2 s .c  o m
    JSONObject param = null;
    JSONObject auth_info = null;
    JSONObject legacy_message = null;
    String progressMsg = "";

    ConfigurationModel cm = ConfigurationModel.getConfigurationModel();

    long start = System.currentTimeMillis();

    try {
        Logger.d(TAG, "doInBackground");

        root = (JSONObject) request.getData();
        param = root.getJSONObject("param");
        //    
        if (param.has("progress_message")) {
            progressMsg = param.getString("progress_message");
            AbstractActivity.PROGRESS_MESSAGE = progressMsg;
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (activity.getDlg() != null) {
                        activity.getDlg().setMessage(AbstractActivity.PROGRESS_MESSAGE);
                    }
                }
            });
        }

        callback = param.getString("callback");
        // ?? .
        //message = param.getJSONObject("message");
        auth_info = param.getJSONObject("auth_info");
        legacy_trcode = param.getString("legacy_trcode");
        legacy_message = param.getJSONObject("legacy_message");

        String password = "";
        String user_id = "";

        password = auth_info.getString("password");
        user_id = auth_info.getString("user_id");

        JSONObject data = new JSONObject();
        JSONObject newParam = new JSONObject();
        JSONObject newMassage = new JSONObject();
        JSONObject newHeader = new JSONObject();
        JSONObject newBody = new JSONObject();

        data.put("param", newParam);
        newParam.put("message", newMassage);
        newMassage.put("header", newHeader);
        newMassage.put("body", newBody);

        newHeader.put("result", true);
        newHeader.put("error_code", "");
        newHeader.put("error_text", "");
        newHeader.put("info_text", "");
        newHeader.put("message_version", "0.9");
        newHeader.put("login_session_id", "");
        newHeader.put("trcode", "LOGIN");

        newBody.put("password", password);
        newBody.put("legacy_trcode", legacy_trcode);
        newBody.put("legacy_message", legacy_message);
        newBody.put("user_id", user_id);

        newBody.put("os_type", Def.OS_TYPE_NAME);

        boolean emulFlag = false;
        if (android.os.Build.MODEL.contains("sdk")) {
            emulFlag = true;
        }

        TelephonyManager manager = (TelephonyManager) request.getSrcActivity()
                .getSystemService(Context.TELEPHONY_SERVICE);
        boolean manual_phone_number = false;

        String mobilenum = "";
        String tempNumber = "";
        if (manager != null) {
            tempNumber = manager.getLine1Number();
            if (tempNumber == null) {
                mobilenum = cm.getStringSharedPreferences("MANUAL_NUMBER");
                manual_phone_number = true;
            } else if (tempNumber.equals("")) {
                manual_phone_number = true;
                mobilenum = cm.getStringSharedPreferences("MANUAL_NUMBER");
            } else {
                if (emulFlag == true) {
                    manual_phone_number = true;
                    mobilenum = cm.getStringSharedPreferences("MANUAL_NUMBER");
                } else {
                    manual_phone_number = false;
                    mobilenum = tempNumber;
                }
            }
        } else {
            mobilenum = cm.getStringSharedPreferences("MANUAL_NUMBER");
            if (mobilenum.equals(ConfigurationModel.PREFERENCE_NOTFOUND)) {
                mobilenum = "";
            }
            manual_phone_number = true;
        }
        String device_id = "";
        if (manager != null) {
            device_id = manager.getDeviceId();
            if (device_id == null) {
                device_id = Secure.getString(activity.getContentResolver(), Secure.ANDROID_ID);
            }
        } else {
            device_id = Secure.getString(activity.getContentResolver(), Secure.ANDROID_ID);
        }
        newBody.put("manual_phone_number", manual_phone_number);
        newBody.put("device_id", device_id);

        // emulator flag true ? device?  ?         
        if (auth_info.has("emulator_flag")) {
            newBody.put("emulator_flag", auth_info.getBoolean("emulator_flag"));
        } else {
            newBody.put("emulator_flag", emulFlag);
        }
        newBody.put("app_key", Def.APPLICTION_NAME);
        newBody.put("phone_number", mobilenum);

        request.setData(data);
        request.setTrCode("LOGIN");

        response.setCallback(callback);

        JSONObject result = sendReq(request);
        JSONObject header = null;
        JSONObject body = null;
        if (result.has("header")) {
            header = result.getJSONObject("header");
        }

        boolean remote = false;
        boolean access_limit = false;

        if (header.getBoolean("result")) {
            if (result.has("body")) {
                body = result.getJSONObject("body");
            }
            // License ?  Login20Task  SUCCESS ? ?? Task  ? ???
            // License ??  ?  
            String device_type = cm.getStringSharedPreferences("device_type");
            Def.LICENSE_NO_VALUE = body.getString("license_no");
            Def.USER_TYPE_VALUE = body.getString("user_type");
            //ActivationTask?  ? ? ??
            Def.DEVICE_TYPE_VALUE = device_type;
            Def.USER_ID_VALUE = user_id;
            Def.DEVICE_ID_VALUE = device_id;
            Def.COMPANY_ID_VALUE = body.getString("company_id");

            //"attachment_download": true,
            //"access_limit": false,
            //"legacy_message": "",
            //"legacy_trcode": ""

            // App Tester 
            boolean app_tester = body.getBoolean("app_tester");
            boolean app_tester_before = cm.getBooleanSharedPreferences(ConfigurationModel.APP_TESTER);
            // Update ? ? ?  ? ??.
            if (app_tester != app_tester_before) {
                String CONTENT_ROOT = ImageUtil.ROOT_PATH + ImageUtil.CONTENT_ROOT + "/";

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "?? .", Toast.LENGTH_LONG).show();
                    }
                });

                File f = new File(CONTENT_ROOT);
                if (f.exists()) {
                    FileUtils.delete(f);
                }

                cm.setBooleanSharedPreferences(ConfigurationModel.APP_TESTER, app_tester);
                cm.setVersionContentMajor(0);
                cm.setVersionContentMinor(0);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, MSG_CHANGE_USER_TYPE, Toast.LENGTH_LONG).show();
                    }
                });
                activity.finish();
                return null;
            }
            // remote wipe
            remote = body.getBoolean("remote_wipe");
            if (remote) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, MSG_REMOTEWPE, Toast.LENGTH_LONG).show();
                    }
                });
                activity.finish();
                return null;
            }
            // assess limmit
            access_limit = body.getBoolean("access_limit");
            if (access_limit) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, MSG_ACCESS_LIMIIT, Toast.LENGTH_LONG).show();
                    }
                });
                activity.finish();
                return null;
            }

            JSONObject reust_legacy_message = body.getJSONObject("legacy_message");
            response.setData(reust_legacy_message);
        } else {
            Logger.d(TAG, "bizMob result false : " + result);
            response.setError(false);
            response.setData(result);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Logger.d(TAG, "Send Error : " + e.getMessage());
        JSONObject root1 = new JSONObject();
        JSONObject header = new JSONObject();
        try {
            root1.put("header", header);
            header.put("result", false);
            if (e instanceof HttpResponseException) { // HTTTP
                header.put("error_code", "HTTP" + ((HttpResponseException) e).getStatusCode());
                header.put("error_text", e.getMessage());
            } else if (e instanceof HttpHostConnectException) { // Connect
                header.put("error_code", "NE0001");
                header.put("error_text", e.getMessage());
            } else if (e instanceof ConnectTimeoutException) { // Connect
                header.put("error_code", "NE0001");
                header.put("error_text", e.getMessage());
            } else if (e instanceof SocketTimeoutException) { // Read 
                header.put("error_code", "NE0002");
                header.put("error_text", e.getMessage());
            } else if (e instanceof IOException) { //  ? ? ? 
                header.put("error_code", "NE0003");
                header.put("error_text", e.getMessage());
            } else if (e instanceof NullPointerException) {
                header.put("error_code", "CE0001"); //  ? ?
                header.put("error_text", "NullPointerException");
            } else {
                header.put("error_code", "CE0001"); //  ? ?
                header.put("error_text", e.getMessage());
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        response.setError(false);
        response.setData(root1);
    } finally {
        //    ??
        if (progressMsg.length() > 0) {
            AbstractActivity.PROGRESS_MESSAGE = AbstractActivity.DEFAULT_PROGRESS_MESSAGE;
        }
        // ?   ??    ?  ?. 
        long end = System.currentTimeMillis();
        long processTime = end - start;
        if (processTime < 200 && processTime > 0) {
            try {
                Thread.sleep(200 - processTime);
            } catch (InterruptedException e) {
            }
        }
    }
    response.setRequest(request);
    setResponse(response);
    return response;

}

From source file:tw.com.sti.store.api.android.AndroidApiService.java

private AndroidApiService(Context context, Configuration config) {
    this.config = config;
    this.apiUrl = new ApiUrl(config);
    if (Logger.DEBUG)
        L.d("new ApiService()");

    sdkVer = Build.VERSION.SDK;//from   ww  w .j av  a2  s  .  c o m
    sdkRel = Build.VERSION.RELEASE;
    try {
        PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(),
                PackageManager.GET_ACTIVITIES);
        storeId = pi.packageName;
        clientVer = "" + pi.versionCode;
    } catch (NameNotFoundException e) {
    }
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    deviceId = tm.getDeviceId() == null ? "0" : tm.getDeviceId();
    macAddress = NetworkUtils.getDeviceMacAddress(context);
    subscriberId = tm.getSubscriberId() == null ? "0" : tm.getSubscriberId();
    simSerialNumber = tm.getSimSerialNumber() == null ? "0" : tm.getSimSerialNumber();

    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    try {
        Class<Display> cls = Display.class;
        Method method = cls.getMethod("getRotation");
        Object retobj = method.invoke(display);
        int rotation = Integer.parseInt(retobj.toString());
        if (Surface.ROTATION_0 == rotation || Surface.ROTATION_180 == rotation) {
            wpx = "" + display.getWidth();
            hpx = "" + display.getHeight();
        } else {
            wpx = "" + display.getHeight();
            hpx = "" + display.getWidth();
        }
    } catch (Exception e) {
        if (display.getOrientation() == 1) {
            wpx = "" + display.getHeight();
            hpx = "" + display.getWidth();
        } else {
            wpx = "" + display.getWidth();
            hpx = "" + display.getHeight();
        }
    }

    SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    //      token = pref.getString(PREF_KEY_TOKEN, "");
    //      uid = pref.getString(PREF_KEY_UID, "");
    //      userId = pref.getString(PREF_KEY_USER_ID, "");
    appFilter = pref.getInt(PREF_KEY_APP_FILTER, 0);
    // ipLoginEnable = pref.getBoolean(PREF_KEY_IP_LOGIN_ENABLE, true);

    // ??SIM?
    String pref_subscriberId = pref.getString(PREF_KEY_SUBSCRIBER_ID, "0");
    String pref_simSerialNumber = pref.getString(PREF_KEY_SIM_SERIAL_NUMBER, "0");
    if (!subscriberId.equals(pref_subscriberId) || !simSerialNumber.equals(pref_simSerialNumber)) {
        if (Logger.DEBUG)
            L.d("Change SIM card.");
        cleanCredential(context);
    }
    this.getCredential(context);
}

From source file:com.wso2.mobile.mdm.api.DeviceInfo.java

/**
*Returns the IMSI Number/*from  w w w .  j  a va  2 s  .  c  om*/
*/
public String getIMSINumber() {
    final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    imsi = tm.getSubscriberId();
    return imsi;
}

From source file:es.uja.photofirma.android.CameraActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.camera_activity);

    logger.appendLog(100, "login usuario satisfactorio");

    //Definicin de elementos visuales involucrados
    lycpt = (ImageView) findViewById(R.id.cameraActivityCameraPhotoTap);
    lyerr = (LinearLayout) findViewById(R.id.cameraActivityErrorHeader);
    lysuc = (LinearLayout) findViewById(R.id.cameraActivitySuccessHeaderTextView);
    lycan = (LinearLayout) findViewById(R.id.cameraActivityCancelHeader);
    lyinf = (LinearLayout) findViewById(R.id.cameraActivityInfoHeader);
    lyupl = (LinearLayout) findViewById(R.id.cameraActivityUploadingHeader);
    lyudone = (LinearLayout) findViewById(R.id.cameraActivitySuccesUploadHeader);
    lyuerr = (LinearLayout) findViewById(R.id.cameraActivityErrorUploadHeader);
    errorText = (TextView) findViewById(R.id.cameraActivityErrorTextView);

    //gestor de servicios de telefonia, para la obtencin del IMEI del terminal
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    if (telephonyManager == null) {
        imeiNumber = getString(R.string.no_imei_available);
    } else {//from  w ww  . ja  va2s. co  m
        imeiNumber = telephonyManager.getDeviceId();
    }

    //Deteccin de los parametros necesarios tras un login exitoso
    if (getIntent().hasExtra("userName") && getIntent().hasExtra("userId")
            && getIntent().hasExtra("userEmail")) {
        userName = getIntent().getExtras().getString("userName");
        userId = getIntent().getExtras().getInt("userId");
        userEmail = getIntent().getExtras().getString("userEmail");
    } else {
        Toast.makeText(getApplicationContext(), getString(R.string.no_user_data_found), Toast.LENGTH_LONG)
                .show();
    }

    final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle("Aviso de privacidad");
    alertDialog.setMessage(getString(R.string.privacy_alert));
    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            alertDialog.dismiss();
        }
    });
    alertDialog.show();

    SharedPreferences prefs = getSharedPreferences("prefsfile", Context.MODE_PRIVATE);
    String myPrefServerIp = prefs.getString("prefIpAddress", "10.0.3.2");
    URL_CONTENT_UPLOAD = "https://" + myPrefServerIp + "/photo@firmaServices/content_upload.php";
}