Example usage for android.content Context getApplicationContext

List of usage examples for android.content Context getApplicationContext

Introduction

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

Prototype

public abstract Context getApplicationContext();

Source Link

Document

Return the context of the single, global Application object of the current process.

Usage

From source file:org.droidparts.net.http.RESTClient.java

public RESTClient(Context ctx, String userAgent, boolean forceApacheHttpClient) {
    this.ctx = ctx.getApplicationContext();
    this.forceApacheHttpClient = forceApacheHttpClient;
    httpClientWorker = useHttpURLConnection() ? null : new HttpClientWorker(userAgent);
    httpURLConnectionWorker = useHttpURLConnection() ? new HttpURLConnectionWorker(userAgent) : null;
    if (cookieJar == null) {
        cookieJar = new CookieJar(ctx);
    }/*from  ww w.  ja v a2 s .co  m*/
    if (Build.VERSION.SDK_INT >= 14) {
        HttpURLConnectionWorker.setHttpResponseCacheEnabled(ctx, true);
    }
}

From source file:com.github.ignition.support.http.IgnitedHttpClient.java

public IgnitedHttpClient(Context context) {
    appContext = context.getApplicationContext();
    setupHttpClient();/*from  w  w  w.j  a  v  a2  s  . c  o  m*/
    appContext.registerReceiver(new ConnectionChangedBroadcastReceiver(this),
            new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}

From source file:im.vector.util.BugReporter.java

/**
 * Send a bug report./*from  w w  w.j ava  2 s .c  o  m*/
 *
 * @param context         the application context
 * @param withDevicesLogs true to include the device logs
 * @param withCrashLogs   true to include the crash logs
 */
private static void sendBugReport(final Context context, final boolean withDevicesLogs,
        final boolean withCrashLogs, final String bugDescription, final IMXBugReportListener listener) {
    new AsyncTask<Void, Integer, String>() {
        @Override
        protected String doInBackground(Void... voids) {
            File bugReportFile = new File(context.getApplicationContext().getFilesDir(), "bug_report");

            if (bugReportFile.exists()) {
                bugReportFile.delete();
            }

            String serverError = null;
            FileWriter fileWriter = null;

            try {
                fileWriter = new FileWriter(bugReportFile);
                JsonWriter jsonWriter = new JsonWriter(fileWriter);
                jsonWriter.beginObject();

                // android bug report
                jsonWriter.name("user_agent").value("Android");

                // logs list
                jsonWriter.name("logs");
                jsonWriter.beginArray();

                // the logs are optional
                if (withDevicesLogs) {
                    List<File> files = org.matrix.androidsdk.util.Log.addLogFiles(new ArrayList<File>());
                    for (File f : files) {
                        if (!mIsCancelled) {
                            jsonWriter.beginObject();
                            jsonWriter.name("lines").value(convertStreamToString(f));
                            jsonWriter.endObject();
                            jsonWriter.flush();
                        }
                    }
                }

                if (!mIsCancelled && (withCrashLogs || withDevicesLogs)) {
                    jsonWriter.beginObject();
                    jsonWriter.name("lines").value(getLogCatError());
                    jsonWriter.endObject();
                    jsonWriter.flush();
                }

                jsonWriter.endArray();

                jsonWriter.name("text").value(bugDescription);

                String version = "";

                if (null != Matrix.getInstance(context).getDefaultSession()) {
                    version += "User : " + Matrix.getInstance(context).getDefaultSession().getMyUserId() + "\n";
                }

                version += "Phone : " + Build.MODEL.trim() + " (" + Build.VERSION.INCREMENTAL + " "
                        + Build.VERSION.RELEASE + " " + Build.VERSION.CODENAME + ")\n";
                version += "Vector version: " + Matrix.getInstance(context).getVersion(true) + "\n";
                version += "SDK version:  " + Matrix.getInstance(context).getDefaultSession().getVersion(true)
                        + "\n";
                version += "Olm version:  "
                        + Matrix.getInstance(context).getDefaultSession().getCryptoVersion(context, true)
                        + "\n";

                jsonWriter.name("version").value(version);

                jsonWriter.endObject();
                jsonWriter.close();

            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + e.getMessage());
                serverError = e.getLocalizedMessage();
            } catch (OutOfMemoryError oom) {
                Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + oom.getMessage());
                serverError = oom.getMessage();

                if (TextUtils.isEmpty(serverError)) {
                    serverError = "Out of memory";
                }
            }

            try {
                if (null != fileWriter) {
                    fileWriter.close();
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground ; failed to close fileWriter " + e.getMessage());
            }

            if (TextUtils.isEmpty(serverError) && !mIsCancelled) {

                // the screenshot is defined here
                // File screenFile = new File(VectorApp.mLogsDirectoryFile, "screenshot.jpg");
                InputStream inputStream = null;
                HttpURLConnection conn = null;
                try {
                    inputStream = new FileInputStream(bugReportFile);
                    final int dataLen = inputStream.available();

                    // should never happen
                    if (0 == dataLen) {
                        return "No data";
                    }

                    URL url = new URL(context.getResources().getString(R.string.bug_report_url));
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setUseCaches(false);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setRequestProperty("Content-Length", Integer.toString(dataLen));
                    // avoid caching data before really sending them.
                    conn.setFixedLengthStreamingMode(inputStream.available());

                    conn.connect();

                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                    byte[] buffer = new byte[8192];

                    // read file and write it into form...
                    int bytesRead;
                    int totalWritten = 0;

                    while (!mIsCancelled && (bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0) {
                        dos.write(buffer, 0, bytesRead);
                        totalWritten += bytesRead;
                        publishProgress(totalWritten * 100 / dataLen);
                    }

                    dos.flush();
                    dos.close();

                    int mResponseCode;

                    try {
                        // Read the SERVER RESPONSE
                        mResponseCode = conn.getResponseCode();
                    } catch (EOFException eofEx) {
                        mResponseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
                    }

                    // if the upload failed, try to retrieve the reason
                    if (mResponseCode != HttpURLConnection.HTTP_OK) {
                        serverError = null;
                        InputStream is = conn.getErrorStream();

                        if (null != is) {
                            int ch;
                            StringBuilder b = new StringBuilder();
                            while ((ch = is.read()) != -1) {
                                b.append((char) ch);
                            }
                            serverError = b.toString();
                            is.close();

                            // check if the error message
                            try {
                                JSONObject responseJSON = new JSONObject(serverError);
                                serverError = responseJSON.getString("error");
                            } catch (JSONException e) {
                                Log.e(LOG_TAG, "doInBackground ; Json conversion failed " + e.getMessage());
                            }

                            // should never happen
                            if (null == serverError) {
                                serverError = "Failed with error " + mResponseCode;
                            }

                            is.close();
                        }
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG,
                            "doInBackground ; failed with error " + e.getClass() + " - " + e.getMessage());
                    serverError = e.getLocalizedMessage();

                    if (TextUtils.isEmpty(serverError)) {
                        serverError = "Failed to upload";
                    }
                } catch (OutOfMemoryError oom) {
                    Log.e(LOG_TAG, "doInBackground ; failed to send the bug report " + oom.getMessage());
                    serverError = oom.getLocalizedMessage();

                    if (TextUtils.isEmpty(serverError)) {
                        serverError = "Out ouf memory";
                    }

                } finally {
                    try {
                        if (null != conn) {
                            conn.disconnect();
                        }
                    } catch (Exception e2) {
                        Log.e(LOG_TAG, "doInBackground : conn.disconnect() failed " + e2.getMessage());
                    }
                }

                if (null != inputStream) {
                    try {
                        inputStream.close();
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "doInBackground ; failed to close the inputStream " + e.getMessage());
                    }
                }
            }
            return serverError;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);

            if (null != listener) {
                try {
                    listener.onProgress((null == progress) ? 0 : progress[0]);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## onProgress() : failed " + e.getMessage());
                }
            }
        }

        @Override
        protected void onPostExecute(String reason) {
            if (null != listener) {
                try {
                    if (mIsCancelled) {
                        listener.onUploadCancelled();
                    } else if (null == reason) {
                        listener.onUploadSucceed();
                    } else {
                        listener.onUploadFailed(reason);
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## onPostExecute() : failed " + e.getMessage());
                }
            }
        }
    }.execute();
}

From source file:com.bingzer.android.driven.Credential.java

public Credential(Context context, String accountName, Token token) {
    this.context = context.getApplicationContext();
    this.accountName = accountName;
    this.token = token;
}

From source file:com.android.xbrowser.DownloadTouchIcon.java

/**
 * Use this ctor to download the touch icon and update the bookmarks database
 * entry for the given url. Used when the user creates a bookmark from
 * within the bookmarks activity and there haven't been any redirects.
 * TODO: Would be nice to set the user agent here so that there is no
 * potential for the three different ctors here to return different icons.
 *//*from  w w  w  .  jav  a2s.co  m*/
public DownloadTouchIcon(Context ctx, ContentResolver cr, String url) {
    mTab = null;
    mContext = ctx.getApplicationContext();
    mContentResolver = cr;
    mOriginalUrl = null;
    mUrl = url;
    mUserAgent = null;
}

From source file:com.android.xbrowser.DownloadTouchIcon.java

/**
 * Use this ctor to store the touch icon in the bookmarks database for
 * the originalUrl so we take account of redirects. Used when the user
 * bookmarks a page from outside the bookmarks activity.
 *///  www. j a  va 2 s. co  m
public DownloadTouchIcon(Tab tab, Context ctx, ContentResolver cr, WebView view) {
    mTab = tab;
    mContext = ctx.getApplicationContext();
    mContentResolver = cr;
    // Store these in case they change.
    mOriginalUrl = view.getOriginalUrl();
    mUrl = view.getUrl();
    mUserAgent = view.getSettings().getUserAgentString();
}

From source file:bolts.MeasurementEvent.java

private MeasurementEvent(Context context, String eventName, Bundle eventArgs) {
    appContext = context.getApplicationContext();
    name = eventName;
    args = eventArgs;
}

From source file:com.microsoft.azure.engagement.shared.EngagementDataPushReceiver.java

@Override
protected Boolean onDataPushBase64Received(Context context, String category, byte[] decodedBody,
        String encodedBody) {//from w w  w .  java 2  s.  com

    String encodedCategory = encodeURIComponent(category);
    addDataPush(context.getApplicationContext(), encodedCategory, encodedBody, true);
    EngagementShared.instance().checkDataPush();

    return true;
}

From source file:com.android.xbrowser.DownloadTouchIcon.java

/**
 * Use this ctor to not store the touch icon in a database, rather add it to
 * the passed Message's data bundle with the key
 * {@link BrowserContract.Bookmarks#TOUCH_ICON} and then send the message.
 *///from   w ww  .  j  av  a  2  s .co m
public DownloadTouchIcon(Context context, Message msg, String userAgent) {
    mMessage = msg;
    mContext = context.getApplicationContext();
    mContentResolver = null;
    mOriginalUrl = null;
    mUrl = null;
    mUserAgent = userAgent;
}

From source file:com.androidzeitgeist.dashwatch.muzei.SourceManager.java

private SourceManager(Context context) {
    mApplicationContext = context.getApplicationContext();
    mSubscriberComponentName = new ComponentName(context, SourceSubscriberService.class);
    mSharedPrefs = context.getSharedPreferences("muzei_art_sources", 0);
    loadStoredData();/*from  w w  w.  j a  v  a  2 s.co m*/
}