Example usage for android.content Context getText

List of usage examples for android.content Context getText

Introduction

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

Prototype

@NonNull
public final CharSequence getText(@StringRes int resId) 

Source Link

Document

Return a localized, styled CharSequence from the application's package's default string table.

Usage

From source file:com.prey.net.PreyWebServices.java

/**
 * Register a new account and get the API_KEY as return In case email is
 * already registered, this service will return an error.
 * //from w  w  w  .  jav a  2  s.  c  o m
 * @throws PreyException
 * 
 */
public PreyAccountData registerNewAccount(Context ctx, String name, String email, String password,
        String deviceType) throws PreyException {
    ///PreyConfig preyConfig = PreyConfig.getPreyConfig(ctx);

    HashMap<String, String> parameters = new HashMap<String, String>();
    /* 
    parameters.put("user[name]", name);
    parameters.put("user[email]", email);
    parameters.put("user[password]", password);
    parameters.put("user[password_confirmation]", password);
    parameters.put("user[referer_user_id]", "");
    parameters.put("user[country_name]", Locale.getDefault().getDisplayCountry());
      */

    parameters.put("name", name);
    parameters.put("email", email);
    parameters.put("password", password);
    parameters.put("password_confirmation", password);
    parameters.put("country_name", Locale.getDefault().getDisplayCountry());

    PreyHttpResponse response = null;
    String xml = "";
    try {
        String apiv2 = FileConfigReader.getInstance(ctx).getApiV2();
        String url = PreyConfig.getPreyConfig(ctx).getPreyUrl().concat(apiv2).concat("signup.json");
        //String url=PreyConfig.getPreyConfig(ctx).getPreyUiUrl().concat("users.xml");
        response = PreyRestHttpClient.getInstance(ctx).post(url, parameters);
        xml = response.getResponseAsString();
    } catch (IOException e) {
        throw new PreyException(ctx.getText(R.string.error_communication_exception).toString(), e);
    }

    String apiKey = "";
    if (xml.contains("\"key\"")) {
        try {
            JSONObject jsnobject = new JSONObject(xml);
            apiKey = jsnobject.getString("key");
        } catch (Exception e) {

        }
    } else {

        if (response != null && response.getStatusLine() != null
                && response.getStatusLine().getStatusCode() > 299) {
            if (response.getStatusLine().getStatusCode() == 422 && xml.indexOf("already") > 0) {
                throw new PreyException(ctx.getString(R.string.error_already_register, ""));
            }
            throw new PreyException(ctx.getString(R.string.error_cant_add_this_device,
                    "[" + response.getStatusLine().getStatusCode() + "]"));
        } else {
            throw new PreyException(ctx.getString(R.string.error_cant_add_this_device, ""));
        }
    }

    PreyHttpResponse responseDevice = registerNewDevice(ctx, apiKey, deviceType);
    String xmlDeviceId = responseDevice.getResponseAsString();
    String deviceId = null;
    if (xmlDeviceId.contains("{\"key\"")) {
        try {
            JSONObject jsnobject = new JSONObject(xmlDeviceId);
            deviceId = jsnobject.getString("key");
        } catch (Exception e) {

        }
    } else {
        throw new PreyException(ctx.getString(R.string.error_cant_add_this_device, ""));
    }

    PreyAccountData newAccount = new PreyAccountData();
    newAccount.setApiKey(apiKey);
    newAccount.setDeviceId(deviceId);
    newAccount.setEmail(email);
    newAccount.setPassword(password);
    newAccount.setName(name);
    return newAccount;
}

From source file:RhodesService.java

private File downloadPackage(String url) throws IOException {
    final Context ctx = RhodesActivity.getContext();

    final Thread thisThread = Thread.currentThread();

    final Runnable cancelAction = new Runnable() {
        public void run() {
            thisThread.interrupt();//from   w  w w  .j a  v a 2 s . com
        }
    };

    BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ACTION_ASK_CANCEL_DOWNLOAD)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                builder.setMessage("Cancel download?");
                AlertDialog dialog = builder.create();
                dialog.setButton(AlertDialog.BUTTON_POSITIVE, ctx.getText(android.R.string.yes),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                cancelAction.run();
                            }
                        });
                dialog.setButton(AlertDialog.BUTTON_NEGATIVE, ctx.getText(android.R.string.no),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // Nothing
                            }
                        });
                dialog.show();
            } else if (action.equals(ACTION_CANCEL_DOWNLOAD)) {
                cancelAction.run();
            }
        }
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_ASK_CANCEL_DOWNLOAD);
    filter.addAction(ACTION_CANCEL_DOWNLOAD);
    ctx.registerReceiver(downloadReceiver, filter);

    File tmpFile = null;
    InputStream is = null;
    OutputStream os = null;
    try {
        updateDownloadNotification(url, -1, 0);

        /*
        List<File> folders = new ArrayList<File>();
        folders.add(Environment.getDownloadCacheDirectory());
        folders.add(Environment.getDataDirectory());
        folders.add(ctx.getCacheDir());
        folders.add(ctx.getFilesDir());
        try {
           folders.add(new File(ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), 0).dataDir));
        } catch (NameNotFoundException e1) {
           // Ignore
        }
        folders.add(Environment.getExternalStorageDirectory());
                
        for (File folder : folders) {
           File tmpRootFolder = new File(folder, "rhodownload");
           File tmpFolder = new File(tmpRootFolder, ctx.getPackageName());
           if (tmpFolder.exists())
              deleteFilesInFolder(tmpFolder.getAbsolutePath());
           else
              tmpFolder.mkdirs();
                   
           File of = new File(tmpFolder, UUID.randomUUID().toString() + ".apk");
           Logger.D(TAG, "Check path " + of.getAbsolutePath() + "...");
           try {
              os = new FileOutputStream(of);
           }
           catch (FileNotFoundException e) {
              Logger.D(TAG, "Can't open file " + of.getAbsolutePath() + ", check next path");
              continue;
           }
           Logger.D(TAG, "File " + of.getAbsolutePath() + " succesfully opened for write, start download app");
                   
           tmpFile = of;
           break;
        }
        */

        tmpFile = ctx.getFileStreamPath(UUID.randomUUID().toString() + ".apk");
        os = ctx.openFileOutput(tmpFile.getName(), Context.MODE_WORLD_READABLE);

        Logger.D(TAG, "Download " + url + " to " + tmpFile.getAbsolutePath() + "...");

        URL u = new URL(url);
        URLConnection conn = u.openConnection();
        int totalBytes = -1;
        if (conn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            totalBytes = httpConn.getContentLength();
        }
        is = conn.getInputStream();

        int downloaded = 0;
        updateDownloadNotification(url, totalBytes, downloaded);

        long prevProgress = 0;
        byte[] buf = new byte[65536];
        for (;;) {
            if (thisThread.isInterrupted()) {
                tmpFile.delete();
                Logger.D(TAG, "Download of " + url + " was canceled");
                return null;
            }
            int nread = is.read(buf);
            if (nread == -1)
                break;

            //Logger.D(TAG, "Downloading " + url + ": got " + nread + " bytes...");
            os.write(buf, 0, nread);

            downloaded += nread;
            if (totalBytes > 0) {
                // Update progress view only if current progress is greater than
                // previous by more than 10%. Otherwise, if update it very frequently,
                // user will no have chance to click on notification view and cancel if need
                long progress = downloaded * 10 / totalBytes;
                if (progress > prevProgress) {
                    updateDownloadNotification(url, totalBytes, downloaded);
                    prevProgress = progress;
                }
            }
        }

        Logger.D(TAG, "File stored to " + tmpFile.getAbsolutePath());

        return tmpFile;
    } catch (IOException e) {
        if (tmpFile != null)
            tmpFile.delete();
        throw e;
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
        try {
            if (os != null)
                os.close();
        } catch (IOException e) {
        }

        mNM.cancel(DOWNLOAD_PACKAGE_ID);
        ctx.unregisterReceiver(downloadReceiver);
    }
}

From source file:com.prey.net.PreyWebServices.java

public PreyHttpResponse registerNewDeviceRemote(Context ctx, String mail, String notificationId,
        String deviceType) throws PreyException {
    PreyConfig preyConfig = PreyConfig.getPreyConfig(ctx);

    String model = Build.MODEL;//from   w w w .j  a  v  a  2 s  .c o  m
    String vendor = "Google";
    if (!PreyConfig.getPreyConfig(ctx).isCupcakeOrAbove())
        vendor = AboveCupcakeSupport.getDeviceVendor();

    HashMap<String, String> parameters = new HashMap<String, String>();
    parameters.put("device[notification_id]", notificationId);
    parameters.put("device[remote_email]", mail);
    parameters.put("device[title]", vendor + " " + model);
    parameters.put("device[device_type]", deviceType);
    parameters.put("device[os]", "Android");
    parameters.put("device[os_version]", Build.VERSION.RELEASE);
    parameters.put("device[referer_device_id]", "");
    parameters.put("device[plan]", "free");
    parameters.put("device[activation_phrase]", preyConfig.getSmsToRun());
    parameters.put("device[deactivation_phrase]", preyConfig.getSmsToStop());
    parameters.put("device[model_name]", model);
    parameters.put("device[vendor_name]", vendor);

    parameters = increaseData(ctx, parameters);
    TelephonyManager mTelephonyMgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
    String imei = mTelephonyMgr.getDeviceId();
    parameters.put("device[physical_address]", imei);

    PreyHttpResponse response = null;
    try {
        String url = "https://panel.preyapp.com/api/v2/remote.json";
        response = PreyRestHttpClient.getInstance(ctx).post(url, parameters);
    } catch (IOException e) {
        throw new PreyException(ctx.getText(R.string.error_communication_exception).toString(), e);
    }

    return response;
}

From source file:github.popeen.dsub.activity.SubsonicActivity.java

private void checkIfServerOutdated() {
    final Context context = this;
    if (!Util.isOffline(context)) {
        new Thread(new Runnable() {
            public void run() {
                SharedPreferences prefs = Util.getPreferences(context);
                String url = Util.getRestUrl(context, "ping") + "&f=json";
                final String input = KakaduaUtil.http_get_contents_all_cert(url);
                final String ip = KakaduaUtil.http_get_contents("https://ip.popeen.com/api/");
                Log.w("pinging", input);
                runOnUiThread(new Runnable() {
                    @Override// ww w.ja  va 2 s  .c  om
                    public void run() {

                        try {
                            JSONObject json = new JSONObject(input);
                            String resp = json.getJSONObject("subsonic-response").getString("booksonic");
                            Log.w("outdated?", resp);
                            TextView t = (TextView) findViewById(R.id.msg);
                            if (t != null) {
                                if (resp.equals("outdated")) {
                                    Log.w(":/", ":/");
                                    t.setText(context.getText(R.string.msg_server_outdated));
                                    t.setVisibility(View.VISIBLE);
                                } else if (resp.equals("outdated_beta") || resp.equals("true")) { //early beta versions only returned "true"
                                    Log.w(":(", ":(");
                                    t.setText(context.getText(R.string.msg_server_outdated_beta));
                                    t.setVisibility(View.VISIBLE);
                                } else {
                                    Log.w(":)", ":)");
                                    t.setVisibility(View.INVISIBLE);
                                    try {
                                        resp = json.getJSONObject("subsonic-response").getString("emulator");
                                        t.setText("Server Emulator: " + resp.toString());
                                        t.setVisibility(View.VISIBLE);
                                    } catch (Exception e) {
                                    }
                                }
                            }
                        } catch (Exception er) {
                            TextView t = (TextView) findViewById(R.id.msg);
                            if (t != null) {
                                Log.w("Network Error", er.toString());
                                if (er.toString().contains("End of input at character 0")) {
                                    try {
                                        JSONObject ipJson = new JSONObject(ip);
                                        String ipResp = ipJson.getString("ip");
                                        t.setText(context.getText(R.string.msg_server_offline));
                                    } catch (Exception e) {
                                        t.setText(context.getText(R.string.msg_noInternet));
                                    }

                                    t.setVisibility(View.VISIBLE);

                                } else {
                                    t.setText(context.getText(R.string.msg_server_notBooksonic));
                                    t.setVisibility(View.VISIBLE);
                                }
                            }
                        }
                    }
                });
            }
        }).start();
    }
}

From source file:com.prey.net.PreyWebServices.java

/**
 * Register a new device for a given API_KEY, needed just after obtain the
 * new API_KEY.//from w ww  .  j  ava 2 s  . c  om
 * 
 * @throws PreyException
 */
private PreyHttpResponse registerNewDevice(Context ctx, String api_key, String deviceType)
        throws PreyException {
    PreyConfig preyConfig = PreyConfig.getPreyConfig(ctx);

    String model = Build.MODEL;
    String vendor = "Google";
    if (!PreyConfig.getPreyConfig(ctx).isCupcakeOrAbove())
        vendor = AboveCupcakeSupport.getDeviceVendor();

    HashMap<String, String> parameters = new HashMap<String, String>();
    parameters.put("api_key", api_key);
    parameters.put("title", vendor + " " + model);
    parameters.put("device_type", deviceType);
    parameters.put("os", "Android");
    parameters.put("os_version", Build.VERSION.RELEASE);
    parameters.put("referer_device_id", "");
    parameters.put("plan", "free");
    parameters.put("activation_phrase", preyConfig.getSmsToRun());
    parameters.put("deactivation_phrase", preyConfig.getSmsToStop());
    parameters.put("model_name", model);
    parameters.put("vendor_name", vendor);

    parameters = increaseData(ctx, parameters);
    TelephonyManager mTelephonyMgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
    //String imsi = mTelephonyMgr.getSubscriberId();
    String imei = mTelephonyMgr.getDeviceId();
    parameters.put("physical_address", imei);

    PreyHttpResponse response = null;
    try {
        String apiv2 = FileConfigReader.getInstance(ctx).getApiV2();
        String url = PreyConfig.getPreyConfig(ctx).getPreyUrl().concat(apiv2).concat("devices.json");
        PreyLogger.d("url:" + url);
        response = PreyRestHttpClient.getInstance(ctx).post(url, parameters);
        PreyLogger.d("response:" + response.getStatusLine() + " " + response.getResponseAsString());
        // No more devices allowed

        if ((response.getStatusLine().getStatusCode() == 302)
                || (response.getStatusLine().getStatusCode() == 422)
                || (response.getStatusLine().getStatusCode() == 403)) {
            throw new NoMoreDevicesAllowedException(
                    ctx.getText(R.string.set_old_user_no_more_devices_text).toString());
        }
        if (response.getStatusLine().getStatusCode() > 299) {
            throw new PreyException(ctx.getString(R.string.error_cant_add_this_device,
                    "[" + response.getStatusLine().getStatusCode() + "]"));
        }
    } catch (IOException e) {
        throw new PreyException(ctx.getText(R.string.error_communication_exception).toString(), e);
    }

    return response;
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

private void setVersionInfo(Context context, String version) {
    if (SystemUtils.isOlderVersion(context, version)) {
        showWarning(context.getText(R.string.warning_older_version), null, WarningType.WARNING);
    }/*from   w w w . ja v a 2  s .  c o m*/
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

private void setLastSeenSeconds(Context context, long seconds) {
    CharSequence statusText = null;
    if (seconds == 0) {
        // it's improbable, but whatever...
        statusText = context.getText(R.string.seen_moment_ago_label);
    } else if (seconds > 0) {
        long stamp = System.currentTimeMillis() - (seconds * 1000);

        Contact contact = getContact();//w w w  . j  ava2  s. c  o  m
        if (contact != null) {
            contact.setLastSeen(stamp);
        }

        // seconds ago relative to our time
        statusText = MessageUtils.formatRelativeTimeSpan(context, stamp);
    }

    if (statusText != null) {
        setCurrentStatusText(statusText);
    }
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static void showOkMessage(final Context context, final int resId, final boolean long_message) {
    if (context == null)
        return;//  w w w. j av a2  s  .c  o m
    showOkMessage(context, context.getText(resId), long_message);
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static void showInfoMessage(final Context context, final int resId, final boolean long_message) {
    if (context == null)
        return;/*from   w w w .  j a v  a2  s.  c o  m*/
    showInfoMessage(context, context.getText(resId), long_message);
}