Example usage for android.os AsyncTask AsyncTask

List of usage examples for android.os AsyncTask AsyncTask

Introduction

In this page you can find the example usage for android.os AsyncTask AsyncTask.

Prototype

public AsyncTask() 

Source Link

Document

Creates a new asynchronous task.

Usage

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

/**
 * Send a bug report.//from w  w w .j  a v  a 2 s  .co  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:ca.ualberta.cmput301.t03.inventory.UserInventoryFragment.java

/**
 * Gets User associated to system config. Loads any data associated to user.
 *
 * @param savedInstanceState/*from   w w w . j  av  a  2  s .  c  om*/
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mActivity = getActivity();
    positionMap = new HashMap<>();
    filters = new ArrayList<>();
    setHasOptionsMenu(true);

    if (getArguments() != null) {
        //            String username = getArguments().getString(ARG_PARAM1);
        user = Parcels.unwrap(getArguments().getParcelable(ARG_PARAM1));
        if (PrimaryUser.getInstance().equals(user)) {
            user = PrimaryUser.getInstance();
        } else {
            //                user = new User(user.getUsername(), getActivity().getApplicationContext());
            try {
                user = PrimaryUser.getInstance().getFriends().getFriend(user.getUsername());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServiceNotAvailableException e) {
                throw new RuntimeException("OFFLINE CANT DO THIS I GUESS");
            }
        }
    } else {
        user = PrimaryUser.getInstance();
    }

    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void[] params) {
            try {
                //                    user = PrimaryUser.getInstance();

                model = user.getInventory();
                if (!PrimaryUser.getInstance().equals(user)) {
                    filters.add(new PrivateFilterCriteria()); //no refresh here
                }
                controller = new UserInventoryController(getContext(), model);

            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServiceNotAvailableException e) {
                throw new RuntimeException("App is offline.", e);
            }
            return null;

        }

        @Override
        protected void onPostExecute(Void o) {
            fragmentSetup(getView());
            setupFab(getView());
        }
    };
    task.execute();

}

From source file:org.sickbeard.SickBeard.java

public SickBeard(String hostname, String port, String api, boolean https, String extraPath, String user,
        String password, boolean trustAll, String trustMe) {
    this.hostname = hostname;
    this.port = port;
    this.extraPath = "/" + extraPath + "/";
    this.path = this.extraPath + "/api/" + api + "/";
    try {//from  w ww .ja  v a 2  s.  c  om
        this.https = https;
        this.scheme = https ? "https" : "http";

        Authenticator.setDefault(new SickAuthenticator(user, password, hostname));
        HostnameVerifier verifier;
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (Exception e) {
        ;
    }
    /***********************************************************
     * ANDROID SPECIFIC START                                  *
     ***********************************************************/
    // start a AsyncTask to try and find the actual api version number
    AsyncTask<Void, Void, CommandsJson> task = new AsyncTask<Void, Void, CommandsJson>() {
        @Override
        protected CommandsJson doInBackground(Void... arg0) {
            try {
                return SickBeard.this.sbGetCommands();
            } catch (Exception e) {
                Log.e("SickBeard", e.getMessage(), e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(CommandsJson result) {
            // do nothing because this is a network error
            if (result == null)
                return;
            try {
                // if we get a version use it
                SickBeard.this.apiVersion = Integer.valueOf(result.api_version);
            } catch (NumberFormatException e) {
                // 2 was the odd float so assume its 2 if we cant get an int
                SickBeard.this.apiVersion = 2;
            }
        }
    };
    task.execute();
    /***********************************************************
     * ANDROID SPECIFIC END                                    *
     ***********************************************************/
}

From source file:microsoft.aspnet.signalr.client.http.android.AndroidHttpConnection.java

@Override
public HttpConnectionFuture execute(final Request request, final ResponseCallback responseCallback) {

    mLogger.log("Create new AsyncTask for HTTP Connection", LogLevel.Verbose);

    final HttpConnectionFuture future = new HttpConnectionFuture();

    final RequestTask requestTask = new RequestTask() {

        AndroidHttpClient mClient;//from   ww  w .  j  a  v  a 2s  . com
        InputStream mResponseStream;

        @Override
        protected Void doInBackground(Void... voids) {
            if (request == null) {
                future.triggerError(new IllegalArgumentException("request"));
            }

            mClient = AndroidHttpClient.newInstance(Platform.getUserAgent());
            mResponseStream = null;
            URI uri;

            try {
                mLogger.log("Create an Android-specific request", LogLevel.Verbose);
                request.log(mLogger);
                HttpRequest realRequest = createRealRequest(request);
                uri = new URI(request.getUrl());

                HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

                mLogger.log("Execute the HTTP Request", LogLevel.Verbose);
                HttpResponse response;

                try {
                    response = mClient.execute(host, realRequest);
                } catch (SocketTimeoutException timeoutException) {
                    closeStreamAndClient();
                    mLogger.log("Timeout executing request: " + timeoutException.getMessage(),
                            LogLevel.Information);

                    future.triggerTimeout(timeoutException);

                    return null;
                }

                mLogger.log("Request executed", LogLevel.Verbose);

                mResponseStream = response.getEntity().getContent();
                Header[] headers = response.getAllHeaders();
                Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                for (Header header : headers) {
                    String headerName = header.getName();
                    if (headersMap.containsKey(headerName)) {
                        headersMap.get(headerName).add(header.getValue());
                    } else {
                        List<String> headerValues = new ArrayList<String>();
                        headerValues.add(header.getValue());
                        headersMap.put(headerName, headerValues);
                    }
                }

                responseCallback.onResponse(new StreamResponse(mResponseStream,
                        response.getStatusLine().getStatusCode(), headersMap));
                future.setResult(null);
                closeStreamAndClient();
            } catch (Exception e) {
                closeStreamAndClient();
                mLogger.log("Error executing request: " + e.getMessage(), LogLevel.Critical);

                future.triggerError(e);
            }

            return null;
        }

        protected void closeStreamAndClient() {
            if (mResponseStream != null) {
                try {
                    mResponseStream.close();
                } catch (IOException e) {
                }
            }

            if (mClient != null) {
                mClient.close();
            }
        }
    };

    future.onCancelled(new Runnable() {

        @Override
        public void run() {
            AsyncTask<Void, Void, Void> cancelTask = new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    requestTask.closeStreamAndClient();
                    return null;
                }
            };

            executeTask(cancelTask);
        }
    });

    executeTask(requestTask);

    return future;
}

From source file:com.example.Android.LoginActivity.java

private void RegisterWithGCMServerInBackground() {
    new AsyncTask<Void, Void, String>() {
        @Override/*from ww w.  j a  va2  s.  c o  m*/
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);

                Constants.RegistrationId = regid;

                // Persist the regID - no need to register again.
                storeRegistrationId(context, regid);
                msg = "Done";
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
                OnPXIInitializationFailed();
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            mDisplay.append(msg + "\n");
            // should send the registration ID to PXI server over HTTP, so it
            // can use GCM to send messages to PXI mobile.
            RegisterWithPXIServer();
        }
    }.execute(null, null, null);
}

From source file:org.deviceconnect.android.deviceplugin.sonycamera.utils.DConnectUtil.java

/**
 * ?????.//from ww  w.  j a va 2  s  .  c om
 * 
 * @param listener ??
 */
public static void asyncSearchDevice(final DConnectMessageHandler listener) {
    AsyncTask<Void, Void, DConnectMessage> task = new AsyncTask<Void, Void, DConnectMessage>() {
        @Override
        protected DConnectMessage doInBackground(final Void... params) {
            try {
                DConnectClient client = new HttpDConnectClient();
                HttpGet request = new HttpGet(DISCOVERY_URI);
                HttpResponse response = client.execute(request);
                return (new HttpMessageFactory()).newDConnectMessage(response);
            } catch (IOException e) {
                return new DConnectResponseMessage(DConnectMessage.RESULT_ERROR);
            }
        }

        @Override
        protected void onPostExecute(final DConnectMessage message) {
            if (listener != null) {
                listener.handleMessage(message);
            }
        }
    };
    task.execute();
}

From source file:com.qiqi8226.http.MainActivity.java

private void onBtnClientGet() {
    new AsyncTask<String, String, Void>() {

        @Override// www  . j  a va 2s . co m
        protected Void doInBackground(String... params) {
            String tmp;
            try {
                tmp = URLEncoder.encode("API", "utf-8");
                HttpGet get = new HttpGet(params[0] + tmp);
                HttpResponse response = client.execute(get);
                tmp = EntityUtils.toString(response.getEntity());
                publishProgress(tmp);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            tv.setText(values[0]);
        }
    }.execute(
            "http://fanyi.youdao.com/openapi.do?keyfrom=qiqi8226&key=1401459950&type=data&doctype=xml&version=1.1&q=");
}

From source file:com.mobicage.rogerthat.util.logging.L.java

private static void logToServer(final String s, final Throwable t) {
    try {//from  w ww  .j av  a2s. c o m
        if (sMainService == null)
            return;
        final long currentTimeMillis = sMainService.currentTimeMillis();
        if (currentTimeMillis - sLastErrorLogTimestamp < MAX_SEND_RATE)
            return;
        sLastErrorLogTimestamp = currentTimeMillis;
        try {
            throw new Exception();
        } catch (final Exception e) {
            if (sMainService.getRegisteredFromConfig()) {
                sMainService.postOnUIHandler(new SafeRunnable() {
                    @Override
                    protected void safeRun() throws Exception {
                        if (sMainService == null)
                            return;
                        LogErrorRequestTO request = new LogErrorRequestTO();
                        request.description = s;
                        request.platform = 1;
                        request.timestamp = currentTimeMillis / 1000;
                        request.mobicageVersion = (sMainService.isDebug() ? "-" : "")
                                + sMainService.getMajorVersion() + "." + sMainService.getMinorVersion();
                        request.platformVersion = Build.FINGERPRINT + " (-) " + SystemUtils.getAndroidVersion()
                                + " (-) " + Build.MODEL;
                        setErrorMessageOnLogErrorRequest(t == null ? e : t, request);
                        Rpc.logError(new ResponseHandler<LogErrorResponseTO>(), request);
                    }
                });
            } else {
                new AsyncTask<Object, Object, Object>() {
                    @Override
                    protected Object doInBackground(Object... params) {
                        if (sMainService == null)
                            return null;
                        try {
                            HttpPost httpPostRequest = new HttpPost(CloudConstants.LOG_ERROR_URL);
                            httpPostRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");

                            RegistrationWizard2 wiz = RegistrationWizard2.getWizard(sMainService);

                            List<NameValuePair> formParams = new ArrayList<NameValuePair>();
                            formParams.add(new BasicNameValuePair("install_id", wiz.getInstallationId()));
                            formParams.add(new BasicNameValuePair("device_id", wiz.getDeviceId()));
                            formParams
                                    .add(new BasicNameValuePair("language", Locale.getDefault().getLanguage()));
                            formParams.add(new BasicNameValuePair("country", Locale.getDefault().getCountry()));
                            formParams.add(new BasicNameValuePair("description", s));
                            formParams.add(new BasicNameValuePair("platform", "1"));
                            formParams.add(new BasicNameValuePair("platform_version",
                                    "" + SystemUtils.getAndroidVersion()));
                            formParams.add(new BasicNameValuePair("timestamp",
                                    "" + System.currentTimeMillis() / 1000));
                            formParams.add(new BasicNameValuePair("mobicage_version",
                                    MainService.getVersion(sMainService)));
                            formParams.add(new BasicNameValuePair("error_message",
                                    getStackTraceString(t == null ? e : t)));

                            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, HTTP.UTF_8);
                            httpPostRequest.setEntity(entity);
                            HTTPUtil.getHttpClient().execute(httpPostRequest);
                        } catch (Exception e1) {
                            L.d("Error while posting error to server", e1);
                        }
                        return null;
                    }
                }.execute();
            }
        }
    } catch (Exception e) {
        L.d("Error while posting error to server", e);
    }
}

From source file:com.stepsdk.android.api.APIClient.java

public void get(final String address, final Map<String, String> headerParams, final APIRequestHandler handler) {
    log(TAG, "GET: " + address);
    new AsyncTask<Void, Void, Void>() {
        private boolean mInterrupt = false;

        @Override/*from ww w  .j  a  v a 2 s  .co  m*/
        protected void onPreExecute() {
            log(TAG, "starting request for " + address);
            handler.before();
        };

        @Override
        protected Void doInBackground(Void... params) {
            Integer retryRemaining = 3;

            while (retryRemaining > 0) {
                try {
                    if (!NetworkUtil.isOnline(mContext)) {
                        handler.onException(new NetworkDownException());
                        return null;
                    }

                    log(TAG, "processing request for " + address);
                    HttpEntity response = getRequest(address, headerParams);
                    handler.onResponse(response);
                    break;
                } catch (ClientProtocolException e) {
                    if (--retryRemaining == 0) {
                        handler.onException(e);
                    }
                } catch (IOException e) {
                    if (--retryRemaining == 0) {
                        handler.onException(e);
                    }
                } catch (NetworkDownException e) {
                    if (--retryRemaining == 0) {
                        handler.onException(e);
                    }
                } catch (HttpGetException e) {
                    if (--retryRemaining == 0) {
                        handler.onException(e);
                    }
                } catch (Exception e) {
                    if (--retryRemaining == 0) {
                        handler.onException(e);
                        e.printStackTrace();
                    }
                }
            }

            return null;
        };

        @Override
        protected void onPostExecute(Void result) {
            log(TAG, "Completed request for " + address);
            if (!mInterrupt)
                handler.after();
        };

    }.execute();
}

From source file:ca.ualberta.cmput301.t03.user.EditProfileFragment.java

/**
 * {@inheritDoc}//  w w  w. j  a  v a 2s.  com
 */
@Override
public void onDestroyView() {
    super.onDestroyView();

    new AsyncTask<Object, Object, Object>() {

        @Override
        protected Object doInBackground(Object... params) {
            controller.commitChanges();
            return null;
        }
    }.execute();

}