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:kr.co.cashqc.MainActivity.java

public String getRegId() {
    final String regId = GCMRegistrar.getRegistrationId(getApplicationContext());
    Log.e("JAY", "regid = " + regId);
    if (regId.equals("")) {
        GCMRegistrar.register(this, SENDER_ID);
        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
    } else {/*from ww w  .  j a  v a2s. c  o m*/
        if (GCMRegistrar.isRegisteredOnServer(this)) {
            // Toast.makeText(getApplicationContext(), "Already",
            // Toast.LENGTH_LONG).show();
        } else {
            final Context context = this;
            mRegisterTask = new AsyncTask<Void, Void, Void>() {

                protected Void doInBackground(Void... params) {
                    ServerUtilities.register(context, "central", getPhoneNumber(), regId);
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    mRegisterTask = null;
                }
            };
            mRegisterTask.execute(null, null, null);
        }
        Log.v("JAY", "Already registered");
    }
    return regId;
}

From source file:com.eugene.fithealthmaingit.UI.NavFragments.FragmentSearch.java

private void searchFood(final String item, final int page_num) {
    if (!NetworkConnectionStatus.isNetworkAvailable(getActivity())) {
        Toast.makeText(getActivity(), "Check your connection and try again", Toast.LENGTH_LONG).show();
    } else {/* w w  w .  j a v  a  2 s  .  co  m*/
        mAsyncTask = new AsyncTask<String, String, String>() {
            @Override
            protected void onPreExecute() {
            }

            @Override
            protected String doInBackground(String... arg0) {
                JSONObject food = mFatSecretSearch.searchFood(item, page_num);
                JSONArray FOODS_ARRAY;
                try {
                    if (food != null) {
                        FOODS_ARRAY = food.getJSONArray("food");
                        if (FOODS_ARRAY != null) {
                            for (int i = 0; i < FOODS_ARRAY.length(); i++) {
                                JSONObject food_items = FOODS_ARRAY.optJSONObject(i);
                                String food_name = food_items.getString("food_name");
                                String food_description = food_items.getString("food_description");
                                String[] row = food_description.split("-");
                                String id = food_items.getString("food_type");
                                if (id.equals("Brand")) {
                                    brand = food_items.getString("brand_name");
                                }
                                if (id.equals("Generic")) {
                                    brand = "Generic";
                                }
                                String food_id = food_items.getString("food_id");
                                mItem.add(new SearchItemResult(food_name, row[1].substring(1), "" + brand,
                                        food_id));
                            }
                        }
                    }
                } catch (JSONException exception) {
                    exception.printStackTrace();
                    return "Error";
                }
                return "";
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                searchAdapter.notifyDataSetChanged();
                if (listContainer.getCount() > 0) {
                    searchBack.setVisibility(View.VISIBLE);
                    TranslateAnimation slide = new TranslateAnimation(0, 0, listContainer.getHeight(), 0);
                    slide.setStartTime(1000);
                    listContainer.setVisibility(View.VISIBLE);
                    slide.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });
                    slide.setDuration(400);
                    listContainer.startAnimation(slide);
                } else {
                    searchBack.setVisibility(View.GONE);
                    listContainer.setVisibility(View.GONE);
                }
            }

            @Override
            protected void onCancelled() {

            }
        };
        mAsyncTask.execute();
    }
}

From source file:com.eugene.fithealthmaingit.UI.ChooseAddMealSearchFragment.java

/**
 * FatSecret Search method.//w w  w  . j  a v a2 s. c om
 * Connect to Rest and return search results based on text and page number
 * Implements FatSecretSearchMethod.class
 *
 * @param item     string to search item
 * @param page_num currently showing 20 items per page. Adds more items if page num increases
 */
private void searchFood(final String item, final int page_num) {
    /**
     * Add Items to the recent database if item is added to the hash set
     */
    for (int i = 0; i < mRecentLogAdapter.getCount(); i++) {
        LogQuickSearch ls = mRecentLogAdapter.getItem(i);
        String name = ls.getName();
        set.add(name.toUpperCase());
    }
    if (set.add(item.toUpperCase())) {
        LogQuickSearch recentLog = new LogQuickSearch();
        recentLog.setName(item);
        recentLog.setDate(new Date());
        recentLog.save();
        mRecentLogAdapter.add(recentLog);
        mRecentLogAdapter.notifyDataSetChanged();
    }

    AsyncTask<String, String, String> mAsyncTask = new AsyncTask<String, String, String>() {
        @Override
        protected void onPreExecute() {
            mSwipeRefreshLayout.setEnabled(true);
            mSwipeRefreshLayout.setRefreshing(true);

        }

        @Override
        protected String doInBackground(String... arg0) {
            JSONObject food = mFatSecretSearch.searchFood(item, page_num);
            JSONArray FOODS_ARRAY;
            try {
                if (food != null) {
                    FOODS_ARRAY = food.getJSONArray("food");
                    if (FOODS_ARRAY != null) {
                        for (int i = 0; i < FOODS_ARRAY.length(); i++) {
                            JSONObject food_items = FOODS_ARRAY.optJSONObject(i);
                            String food_name = food_items.getString("food_name");
                            String food_description = food_items.getString("food_description");
                            String[] row = food_description.split("-");
                            String id = food_items.getString("food_type");
                            if (id.equals("Brand")) {
                                brand = food_items.getString("brand_name");
                            }
                            if (id.equals("Generic")) {
                                brand = "Generic";
                            }
                            String food_id = food_items.getString("food_id");
                            mItem.add(
                                    new SearchItemResult(food_name, row[1].substring(1), "" + brand, food_id));
                        }
                    }
                }
            } catch (JSONException exception) {
                exception.printStackTrace();
                return "Error";
            }
            return "";
        }

        @Override
        protected void onCancelled() {
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result.equals("Error"))
                Toast.makeText(getActivity(), "No Items Containing Your Search", Toast.LENGTH_SHORT).show();
            mSwipeRefreshLayout.setRefreshing(false);
            mSwipeRefreshLayout.setEnabled(false);
            updateListView();
        }
    };
    mAsyncTask.execute();
}

From source file:com.ibm.mf.geofence.MFGeofencingManager.java

/**
 * Load a set of geofences from a reosurce file.
 * @param resource the path to the resource to load the geofences from.
 *///from w  w w  .j  ava2s .c  o  m
public void loadGeofencesFromResource(final String resource) {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        private GeofenceList geofenceList;
        private HttpRequestError error;

        @Override
        protected Void doInBackground(Void... params) {
            ZipInputStream zis = null;
            try {
                InputStream is = getClass().getClassLoader().getResourceAsStream(resource);
                zis = new ZipInputStream(is);
                ZipEntry entry;
                Map<String, PersistentGeofence> allGeofences = new HashMap<>();
                while ((entry = zis.getNextEntry()) != null) {
                    byte[] bytes = GeofencingUtils.loadBytes(zis);
                    if (bytes != null) {
                        int fileSize = bytes.length;
                        JSONObject json = new JSONObject(new String(bytes, "UTF-8"));
                        bytes = null; // the byte[] may be large, we make sure it can be GC-ed ASAP
                        GeofenceList list = GeofencingJSONUtils.parseGeofences(json);
                        List<PersistentGeofence> geofences = list.getGeofences();
                        if ((geofences != null) && !geofences.isEmpty()) {
                            PersistentGeofence.saveInTx(geofences);
                            log.debug(String.format(Locale.US,
                                    "loaded %,d geofences from resource '[%s]/%s' (%,d bytes)",
                                    geofences.size(), resource, entry.getName(), fileSize));
                        }

                        for (PersistentGeofence pg : list.getGeofences()) {
                            allGeofences.put(pg.getCode(), pg);
                        }
                    } else {
                        log.debug(String.format("the zip entry [%s]/%s is empty", resource, entry.getName()));
                    }
                }
                geofenceList = new GeofenceList(new ArrayList<>(allGeofences.values()));
                log.debug(String.format(Locale.US, "loaded %,d geofences from resource '[%s]'",
                        allGeofences.size(), resource));
            } catch (Exception e) {
                error = new HttpRequestError(-1, e, String.format("error loading resource '%s'", resource));
            } finally {
                try {
                    zis.close();
                } catch (Exception e) {
                    log.error(String.format("error closing zip input stream for resource %s", resource), e);
                    if (error == null) {
                        error = new HttpRequestError(-1, e,
                                String.format("error loading resource '%s'", resource));
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (error != null) {
                log.error(String.format("error loading resource %s : %s", resource, error));
            } else {
                try {
                    Intent broadcastIntent = new Intent(MFGeofenceEvent.ACTION_GEOFENCE_EVENT);
                    broadcastIntent.setPackage(mContext.getPackageName());
                    MFGeofenceEvent.toIntent(broadcastIntent, MFGeofenceEvent.Type.SERVER_SYNC,
                            geofenceList.getGeofences(), null);
                    mContext.sendBroadcast(broadcastIntent);
                } catch (Exception e) {
                    log.error("error sending broadcast event", e);
                }
            }
        }
    };
    task.execute();
}

From source file:org.droid2droid.internal.AbstractRemoteAndroidImpl.java

public void pushMe(final Context context, final PublishListener listener, final int bufsize, final int flags,
        final long timeout) throws RemoteException, IOException {
    new AsyncTask<PublishListener, Integer, Object>() {

        private PublishListener listener;

        @Override/*www. j a v a2  s. com*/
        protected Object doInBackground(PublishListener... params) {
            listener = params[0];
            FileInputStream in = null;
            int fd = -1;
            int connid = -1;
            int s;
            byte[] buf = new byte[bufsize];
            byte[] signature = null;
            try {
                PackageManager pm = context.getPackageManager();
                ApplicationInfo info = Droid2DroidManagerImpl.sAppInfo;
                String label = context.getString(info.labelRes);
                PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
                File filename = new File(info.publicSourceDir);

                int versionCode = pi.versionCode;
                signature = pi.signatures[0].toByteArray();

                long length = filename.length();
                connid = getConnectionId();
                if (V)
                    Log.v(TAG_INSTALL, PREFIX_LOG + "CLI propose apk " + info.packageName);
                fd = proposeApk(connid, label, info.packageName, versionCode, signature, length, flags,
                        timeout);
                if (fd > 0) {
                    // TODO: ask sender before send datas
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI it's accepted");
                    in = new FileInputStream(filename);
                    StringBuilder prog = new StringBuilder();
                    // TODO: multi thread for optimize read latency ?
                    long timeoutSendFile = 30000; // FIXME: Time out pour send file en dur.
                    long pos = 0;
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI send file");
                    while ((s = in.read(buf, 0, buf.length)) > 0) {
                        if (V) {
                            prog.append('*');
                            if (V)
                                Log.v(TAG_INSTALL, PREFIX_LOG + "" + prog.toString()); // TODO: A garder ?
                        }
                        if (!sendFileData(connid, fd, buf, s, pos, length, timeoutSendFile)) {
                            if (E)
                                Log.e(TAG_INSTALL, PREFIX_LOG + "Impossible to send file data");
                            throw new RemoteException();
                        }
                        pos += s;
                        publishProgress((int) ((double) pos / length * 10000L));
                    }
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI send file done");
                    if (installApk(connid, label, fd, flags, timeout)) {
                        if (V)
                            Log.v(TAG_INSTALL, PREFIX_LOG + "CLI apk is installed");
                        return 1;
                    } else {
                        if (V)
                            Log.v(TAG_INSTALL, PREFIX_LOG + "CLI install apk is canceled");
                        return new CancellationException("Install apk " + pi.packageName + " is canceled");
                    }
                } else {
                    if (V)
                        Log.v(TAG_INSTALL, PREFIX_LOG + "CLI install apk is accepted (" + fd + ")");
                    return fd;
                }
            } catch (NameNotFoundException e) {
                cancelCurrentUpload(timeout, fd, connid);
                return e;
            } catch (IOException e) {
                cancelCurrentUpload(timeout, fd, connid);
                return e;
            } catch (RemoteException e) {
                if (D)
                    Log.d(TAG_INSTALL, "Impossible to push apk (" + e.getMessage() + ")", e);
                cancelCurrentUpload(timeout, fd, connid);
                return e;
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // Ignore
                    }
                }
            }
        }

        private void cancelCurrentUpload(final long timeout, int fd, int connid) {
            if (connid != -1 && fd != -1) {
                try {
                    cancelFileData(connid, fd, timeout);
                } catch (RemoteException e1) {
                    // Ignore
                }
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            postPublishProgress(listener, values[0]);
        }

        @Override
        protected void onPostExecute(Object result) {
            if (result instanceof Throwable) {
                postPublishError(listener, (Throwable) result);
            } else
                postPublishFinish(listener, ((Integer) result).intValue());
        }
    }.execute(listener);
}

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

/**
 * ???.//w w w. j  a  va  2  s .  c om
 * 
 * @param deviceId ?ID
 * @param mediaId ID
 * @param listener 
 */
public static void asyncStopMovie(final String deviceId, final String mediaId,
        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();
                HttpPut request = new HttpPut(
                        MEDIASTREAM_STOP + "?deviceId=" + deviceId + "&mediaId=" + mediaId);
                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.example.carrie.carrie_test1.druginfo.java

private void load_data_from_server_search(final String search) {
    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override//  w  w w.jav a 2 s .co  m
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url("http://54.65.194.253/Drug/search.php?search=" + search)
                    .build();
            Log.d("searchtest", "4");
            try {
                Response response = client.newCall(request).execute();

                JSONArray array = new JSONArray(response.body().string());
                Log.d("searchtest", array.toString());
                for (int i = 0; i < array.length(); i++) {

                    JSONObject object = array.getJSONObject(i);

                    MyData mydata = new MyData(object.getInt("id"), object.getString("chineseName"),
                            object.getString("image"), object.getString("indication"),
                            object.getString("englishName"), object.getString("licenseNumber"),
                            object.getString("category"), object.getString("component"),
                            object.getString("maker_Country"), object.getString("applicant"),
                            object.getString("maker_Name"), object.getString("QRCode"));

                    data_list2.add(mydata);
                }
                Log.d("searchtest", "5");

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                System.out.println("End of content");
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            adapter.notifyDataSetChanged();
        }
    };

    task.execute(1);
}

From source file:ca.rmen.android.scrumchatter.main.MainActivity.java

/**
 * Called when the current team was changed. Update our cache of the current team and update the ui (menu items, action bar title).
 *///from w  w w  . j  av  a  2  s . c  o m
private void onTeamChanged() {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... arg0) {
            mTeam = mTeams.getCurrentTeam();
            // If for some reason we have no current team, select any available team
            // Should not really happen, so perhaps this check should be removed?
            if (mTeam == null) {
                mTeams.selectFirstTeam();
            }
            mTeamCount = mTeams.getTeamCount();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // If the user has renamed the default team or added other teams, show the current team name in the title
            if (mTeamCount > 1 || (mTeam != null && !mTeam.teamName.equals(Constants.DEFAULT_TEAM_NAME)))
                getSupportActionBar().setTitle(mTeam.teamName);
            // otherwise the user doesn't care about team management: just show the app title.
            else
                getSupportActionBar().setTitle(R.string.app_name);
            supportInvalidateOptionsMenu();
        }
    };
    task.execute();
}

From source file:com.mobilesolutionworks.android.twitter.TwitterPluginFragment.java

@SuppressWarnings("unchecked")
protected Task<RequestToken> doGetAuthenticationURL(final Twitter instance) {
    final Task<RequestToken>.TaskCompletionSource source = Task.create();

    new AsyncTask<Task<RequestToken>.TaskCompletionSource, Void, Object>() {
        @Override//w ww  .j  av a  2s . c o m
        protected Object doInBackground(Task<RequestToken>.TaskCompletionSource... params) {
            try {
                return instance.getOAuthRequestToken("oauth://works-twitter");
            } catch (TwitterException e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object s) {
            super.onPostExecute(s);
            if (s instanceof RequestToken) {
                source.trySetResult((RequestToken) s);
            } else {
                source.trySetError((Exception) s);
            }
        }
    }.execute(source);
    return source.getTask();
}

From source file:com.df.push.DemoActivity.java

private void getTopics() {
    final String url = "https://next.cloud.dreamfactory.com/rest/sns/topic?app_name=todoangular";

    new AsyncTask<Void, Void, String>() {
        @Override/* www.j av a 2 s  . c o  m*/
        protected String doInBackground(Void... params) {
            String msg = "";
            HttpResponse<JsonNode> jsonResponse;
            try {
                jsonResponse = Unirest.get(url).header("accept", "application/json").asJson();
                JSONArray topicsArray = jsonResponse.getBody().getObject().getJSONArray("resource");
                for (int i = 0; i < topicsArray.length(); i++) {
                    topics.add(topicsArray.getJSONObject(i).getString("Topic"));
                }
                Log.i(TAG, "Get Topic Response " + topics.toString());

            } catch (Exception e) {
                msg = e.getLocalizedMessage();
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            //            mDisplay.append(msg + "\n")
            progressDialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            if (progressDialog != null)
                progressDialog.show();
        };
    }.execute(null, null, null);
}