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:Main.java

public static void jumpPostToActivity(final Context context, final Class<? extends Activity> targetClass,
        final int second, final String... datas) {
    (new AsyncTask<String, Integer, Boolean>() {
        protected Boolean doInBackground(String... params) {
            try {
                Thread.sleep((long) (second * 1000));
            } catch (Exception var3) {
                ;//from w ww . j a  va2s . c  om
            }
            return null;
        }

        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            Intent datatIntent = new Intent(context, targetClass);
            if (datas != null) {
                for (int i = 0; i < datas.length; ++i) {
                    datatIntent.putExtra("data" + i, datas[i]);
                }
            }

            context.startActivity(datatIntent);
        }
    }).execute(new String[] { "" });
}

From source file:mc.lib.network.AsyncNetworkHelper.java

public static void saveToFile(final String url, final File file, final OnCompleteListener<File> listener) {
    new AsyncTask<Void, Void, File>() {
        @Override/*from  ww w .jav a2 s. co m*/
        protected File doInBackground(Void... params) {
            NetworkHelper.saveToFile(url, file);
            return file;
        }

        @Override
        protected void onPostExecute(File res) {
            super.onPostExecute(res);
            listener.complete(res);
        }
    }.execute((Void) null);
}

From source file:fr.shywim.antoinedaniel.utils.GcmUtils.java

public static void registerInBackground(final Context context, final GoogleCloudMessaging gcm) {
    new AsyncTask<Void, Void, Void>() {
        @Override//from w  w  w. j a  v  a  2s.c o m
        protected Void doInBackground(Void... params) {
            try {
                String regid = gcm.register(AppConstants.SENDER_ID);
                sendRegistrationIdToBackend(context, regid, Utils.getAppVersion(context));
                storeRegistrationId(context, regid);
            } catch (IOException ex) {
                Crashlytics.logException(ex);
            }
            return null;
        }
    }.execute(null, null, null);
}

From source file:br.com.cybereagle.androidtestlibrary.shadow.ShadowAsyncTaskLoader.java

@Implementation
void executePendingTask() {
    new AsyncTask<Void, Void, D>() {
        @Override//from www  . j av  a2 s .  co m
        protected D doInBackground(Void... params) {
            return (D) asyncTaskLoader.loadInBackground();
        }

        @Override
        protected void onPostExecute(D data) {
            updateLastLoadCompleteTimeField();
            asyncTaskLoader.deliverResult(data);
        }

        @Override
        protected void onCancelled(D data) {
            updateLastLoadCompleteTimeField();
            asyncTaskLoader.onCanceled(data);

            executePendingTask();
        }
    };
}

From source file:com.facebook.fresco.sample.urlsfetcher.ImageUrlsFetcher.java

public static void getImageUrls(final ImageUrlsRequest request, final Callback callback) {
    new AsyncTask<Void, Void, List<String>>() {
        @Override//w w w  .ja  va  2 s.co m
        protected List<String> doInBackground(Void... params) {
            return getImageUrls(request);
        }

        @Override
        protected void onPostExecute(List<String> result) {
            callback.onFinish(result);
        }
    }.execute();
}

From source file:com.xfinity.ceylon_steel.controller.CustomerController.java

public static void downloadCustomers(final Context context) {
    new AsyncTask<User, Void, JSONArray>() {

        @Override/*from w w  w .  j  a  v a 2  s .  c  om*/
        protected void onPreExecute() {
            if (UserController.progressDialog == null) {
                UserController.progressDialog = new ProgressDialog(context);
                UserController.progressDialog.setMessage("Downloading Data");
                UserController.progressDialog.setCanceledOnTouchOutside(false);
            }
            if (!UserController.progressDialog.isShowing()) {
                UserController.progressDialog.show();
            }
        }

        @Override
        protected JSONArray doInBackground(User... users) {
            try {
                User user = users[0];
                HashMap<String, Object> parameters = new HashMap<String, Object>();
                parameters.put("userId", user.getUserId());
                return getJsonArray(getCustomersOfUser, parameters, context);
            } catch (IOException ex) {
                Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (JSONException ex) {
                Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONArray result) {
            if (UserController.atomicInteger.decrementAndGet() == 0 && UserController.progressDialog != null
                    && UserController.progressDialog.isShowing()) {
                UserController.progressDialog.dismiss();
                UserController.progressDialog = null;
            }
            if (result != null) {
                SQLiteDatabaseHelper databaseInstance = SQLiteDatabaseHelper.getDatabaseInstance(context);
                SQLiteDatabase database = databaseInstance.getWritableDatabase();
                SQLiteStatement compiledStatement = database
                        .compileStatement("replace into tbl_customer(customerId,customerName) values(?,?)");
                try {
                    database.beginTransaction();
                    for (int i = 0; i < result.length(); i++) {
                        JSONObject customer = result.getJSONObject(i);
                        compiledStatement.bindAllArgsAsStrings(
                                new String[] { Integer.toString(customer.getInt("customerId")),
                                        customer.getString("customerName") });
                        long response = compiledStatement.executeInsert();
                        if (response == -1) {
                            return;
                        }
                    }
                    database.setTransactionSuccessful();
                    Toast.makeText(context, "Customers downloaded successfully", Toast.LENGTH_SHORT).show();
                } catch (JSONException ex) {
                    Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
                    Toast.makeText(context, "Unable parse customers", Toast.LENGTH_SHORT).show();
                } finally {
                    database.endTransaction();
                    databaseInstance.close();
                }
            } else {
                Toast.makeText(context, "Unable to download customers", Toast.LENGTH_SHORT).show();
            }
        }

    }.execute(UserController.getAuthorizedUser(context));
}

From source file:cn.figo.mydemo.content.RecentMediaStorage.java

public void saveUrlAsync(String url) {
    new AsyncTask<String, Void, Void>() {
        @Override// w ww . j a  v  a2 s  .c  o m
        protected Void doInBackground(String... params) {
            saveUrl(params[0]);
            return null;
        }
    }.execute(url);
}

From source file:org.jorge.lolin1.io.net.HTTPServices.java

public static void downloadFile(final String whatToDownload, final File whereToSaveIt) throws IOException {
    logString("debug", "Downloading url " + whatToDownload);
    AsyncTask<Void, Void, Object> imageDownloadAsyncTask = new AsyncTask<Void, Void, Object>() {
        @Override//  w  w  w.  j  a  va 2s . c  o m
        protected Object doInBackground(Void... params) {
            Object ret = null;
            BufferedInputStream bufferedInputStream = null;
            FileOutputStream fileOutputStream = null;
            try {
                logString("debug", "Opening stream for " + whatToDownload);
                bufferedInputStream = new BufferedInputStream(
                        new URL(URLDecoder.decode(whatToDownload, "UTF-8").replaceAll(" ", "%20"))
                                .openStream());
                logString("debug", "Opened stream for " + whatToDownload);
                fileOutputStream = new FileOutputStream(whereToSaveIt);

                final byte data[] = new byte[1024];
                int count;
                logString("debug", "Loop-writing " + whatToDownload);
                while ((count = bufferedInputStream.read(data, 0, 1024)) != -1) {
                    fileOutputStream.write(data, 0, count);
                }
                logString("debug", "Loop-written " + whatToDownload);
            } catch (IOException e) {
                return e;
            } finally {
                if (bufferedInputStream != null) {
                    try {
                        bufferedInputStream.close();
                    } catch (IOException e) {
                        ret = e;
                    }
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        ret = e;
                    }
                }
            }
            return ret;
        }
    };
    imageDownloadAsyncTask.executeOnExecutor(fileDownloadExecutor);
    Object returned = null;
    try {
        returned = imageDownloadAsyncTask.get();
    } catch (ExecutionException | InterruptedException e) {
        Crashlytics.logException(e);
    }
    if (returned != null) {
        throw (IOException) returned;
    }
}

From source file:at.jclehner.appopsxposed.BugReportBuilder.java

public static void buildAndSend(final Context context) {
    if (!SU.available()) {
        Toast.makeText(context, R.string.toast_needs_root, Toast.LENGTH_SHORT).show();
        return;//from   w w  w. j av a 2  s  .c  om
    }

    Toast.makeText(context, R.string.building_toast, Toast.LENGTH_LONG).show();

    final BugReportBuilder brb = new BugReportBuilder(context);

    new AsyncTask<Void, Void, Uri>() {

        @Override
        protected Uri doInBackground(Void... params) {
            return brb.build();
        }

        @Override
        protected void onPostExecute(Uri result) {
            final ArrayList<Parcelable> uris = new ArrayList<Parcelable>();
            uris.add(result);

            final Intent target = new Intent(Intent.ACTION_SEND_MULTIPLE);
            target.setType("text/plain");
            target.putExtra(Intent.EXTRA_SUBJECT,
                    "[REPORT][AppOpsXposed " + Util.getAoxVersion(context) + "] " + Build.FINGERPRINT);
            target.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
            //target.putExtra(Intent.EXTRA_STREAM, result);
            target.putExtra(Intent.EXTRA_TEXT, "!!! BUG REPORTS WITHOUT ADDITIONAL INFO WILL BE IGNORED !!!");
            //target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            final Intent intent = Intent.createChooser(target, null);
            //intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            context.startActivity(intent);
        }
    }.execute();
}

From source file:com.vinexs.tool.NetworkManager.java

public static void haveInternet(Context context, final OnInternetResponseListener listener) {
    if (!haveNetwork(context)) {
        listener.onResponsed(false);/*from w w w .  j av a  2  s. c  o  m*/
        return;
    }
    Log.d("Network", "Check internet is reachable ...");
    new AsyncTask<Void, Integer, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                InetAddress ipAddr = InetAddress.getByName("google.com");
                if (ipAddr.toString().equals("")) {
                    throw new Exception("Cannot resolve host name, no internet behind network.");
                }
                HttpURLConnection conn = (HttpURLConnection) new URL("http://google.com/").openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setConnectTimeout(3500);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                DataOutputStream postOutputStream = new DataOutputStream(conn.getOutputStream());
                postOutputStream.write('\n');
                postOutputStream.close();
                conn.disconnect();
                Log.d("Network", "Internet is reachable.");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("Network", "Internet is unreachable.");
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            listener.onResponsed(result);
        }
    }.execute();
}