當前位置: 首頁>>代碼示例>>Java>>正文


Java AsyncTask類代碼示例

本文整理匯總了Java中android.os.AsyncTask的典型用法代碼示例。如果您正苦於以下問題:Java AsyncTask類的具體用法?Java AsyncTask怎麽用?Java AsyncTask使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


AsyncTask類屬於android.os包,在下文中一共展示了AsyncTask類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: ServiceModel

import android.os.AsyncTask; //導入依賴的package包/類
public ServiceModel(){
    super();

    categoryTask = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            CategoryService client = CategoryServiceFactory.getInstance();
            try {
                CategoryModel c = client.get(categoryId).execute().body();
                categoryModel = c;
            } catch (IOException e) {
                Log.e("AppointmentsModel", "Error loading category");
            }

            return (Void)null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            categoryTask = null;
        }
    };
}
 
開發者ID:alextselegidis,項目名稱:easyappointments-android-client,代碼行數:24,代碼來源:ServiceModel.java

示例2: onStartCommand

import android.os.AsyncTask; //導入依賴的package包/類
/**
 * Function to start service
 *
 * @param intent  Activity intent
 * @param flags   to start sticky or not
 * @param startId Service id
 * @return usually start or start once
 */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("TAFSEER_DOWN_TAG" , "tafseer service is start");
    AppPreference.Downloading(true);
    Bundle extras = intent.getExtras();
    String downloadURL = extras.getString(AppConstants.Download.DOWNLOAD_URL);
    String downloadLocation = extras.getString(AppConstants.Download.DOWNLOAD_LOCATION);
    int type = extras.getInt(AppConstants.Download.TYPE , -1);
    List<String> downloadLinks = extras.getStringArrayList(AppConstants.Download.DOWNLOAD_LINKS);

    if(downloadLinks == null){
            downloadManager = new DownloadManager(this, true ,type);
            downloadManager.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, downloadURL, downloadLocation);
    } else{
            downloadManager = new DownloadManager(this, true, downloadLinks ,type);
            downloadManager.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "", downloadLocation);
    }

    return START_NOT_STICKY;
}
 
開發者ID:fekracomputers,項目名稱:QuranAndroid,代碼行數:29,代碼來源:DownloadTafseerService.java

示例3: onRecorderCanceled

import android.os.AsyncTask; //導入依賴的package包/類
@Override
public void onRecorderCanceled() {
  Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
  vibrator.vibrate(50);
  getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

  ListenableFuture<Pair<Uri, Long>> future = audioRecorder.stopRecording();
  future.addListener(new ListenableFuture.Listener<Pair<Uri, Long>>() {
    @Override
    public void onSuccess(final Pair<Uri, Long> result) {
      new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
          PersistentBlobProvider.getInstance(ConversationActivity.this).delete(result.first);
          return null;
        }
      }.execute();
    }

    @Override
    public void onFailure(ExecutionException e) {}
  });
}
 
開發者ID:CableIM,項目名稱:Cable-Android,代碼行數:24,代碼來源:ConversationActivity.java

示例4: initList

import android.os.AsyncTask; //導入依賴的package包/類
private void initList() {
    new AsyncTask<Object, Object, Object>() {
        @Override
        protected Object doInBackground(Object... params) {
            if (currentPage == 0) {
                Cursor foldersCursor = folderDao.getAllFolderCursor();
                adapter = new FoldersAdapter(getContext(), foldersCursor, 0, folderDao);
            } else if (currentPage == 1) {
                Cursor roadsCursor = null;
                if (selectedFolder < 0) {
                    roadsCursor = roadDao.getAllRoadCursor();
                } else {
                    roadsCursor = roadDao.getAllRoadByFolderIdCursor(selectedFolder);
                }
                adapter = new RoadsAdapter(getContext(), roadsCursor, 0, roadDao, selectedFolder);
            }
            return null;
        }
        @Override
        protected void onPostExecute(Object o) {
            setupTitle();
            valuesList.setAdapter(adapter);
        }
    }.execute();
}
 
開發者ID:WorldBank-Transport,項目名稱:RoadLab-Pro,代碼行數:26,代碼來源:SelectProjectDialog.java

示例5: onStartJob

import android.os.AsyncTask; //導入依賴的package包/類
/**
 * The entry point to your Job. Implementations should offload work to another thread of
 * execution as soon as possible.
 *
 * This is called by the Job Dispatcher to tell us we should start our job. Keep in mind this
 * method is run on the application's main thread, so we need to offload work to a background
 * thread.
 *
 * @return whether there is more work remaining.
 */
@Override
public boolean onStartJob(final JobParameters jobParameters) {

    mFetchWeatherTask = new AsyncTask<Void, Void, Void>(){
        @Override
        protected Void doInBackground(Void... voids) {
            Context context = getApplicationContext();
            SunshineSyncTask.syncWeather(context);
            jobFinished(jobParameters, false);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            jobFinished(jobParameters, false);
        }
    };

    mFetchWeatherTask.execute();
    return true;
}
 
開發者ID:rashikaranpuria,項目名稱:ubiquitous,代碼行數:32,代碼來源:SunshineFirebaseJobService.java

示例6: onStartCommand

import android.os.AsyncTask; //導入依賴的package包/類
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    String url = " ";
    int position = -1;

    if (intent != null) {
        url = intent.getStringExtra("url");
        position = intent.getIntExtra("position", -1);
    }

    String[] params = new String[]{url, String.valueOf(position)};
    new DownloadingTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);

    return START_NOT_STICKY;
}
 
開發者ID:webianks,項目名稱:PlayStoreParallelDownload,代碼行數:17,代碼來源:DownloadService.java

示例7: InviteReminder

import android.os.AsyncTask; //導入依賴的package包/類
public InviteReminder(final @NonNull Context context,
                      final @NonNull Recipients recipients)
{
  super(context.getString(R.string.reminder_header_invite_title),
        context.getString(R.string.reminder_header_invite_text, recipients.toShortString()));

  setDismissListener(new OnClickListener() {
    @Override public void onClick(View v) {
      new AsyncTask<Void,Void,Void>() {

        @Override protected Void doInBackground(Void... params) {
          DatabaseFactory.getRecipientPreferenceDatabase(context).setSeenInviteReminder(recipients, true);
          return null;
        }
      }.execute();
    }
  });
}
 
開發者ID:CableIM,項目名稱:Cable-Android,代碼行數:19,代碼來源:InviteReminder.java

示例8: onPreferenceTreeClick

import android.os.AsyncTask; //導入依賴的package包/類
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
    final String key = preference.getKey();
    switch (key) {
        case KEY_CHECK_UPDATE:
            mTask = CheckUpdateTask.getInstance(false);
            if (!mTask.getStatus().equals(AsyncTask.Status.RUNNING)) {
                mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, getActivity());
            }
            return true;
        case KEY_CHANGELOG:
            ChangelogFragment changelogFrag = new ChangelogFragment();
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            transaction.replace(this.getId(), changelogFrag);
            transaction.addToBackStack(this.getClass().getName());
            transaction.commit();
            return true;
        default:
            OTALink link = LinkConfig.getInstance().findLink(key, getActivity());
            if (link != null) {
                OTAUtils.launchUrl(link.getUrl(), getActivity());
            }
            break;
    }
    return super.onPreferenceTreeClick(preferenceScreen, preference);
}
 
開發者ID:DroidThug,項目名稱:VulcanOTA,代碼行數:28,代碼來源:SlimOTAFragment.java

示例9: unregisterActivity

import android.os.AsyncTask; //導入依賴的package包/類
private static void unregisterActivity(final Activity activity) {
    ThreadUtils.assertOnUiThread();

    sPendingShareActivities.remove(activity);
    if (!sPendingShareActivities.isEmpty()) return;
    ApplicationStatus.unregisterActivityStateListener(sStateListener);

    waitForPendingStateChangeTask();
    sStateChangeTask = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            if (!sPendingShareActivities.isEmpty()) return null;

            activity.getPackageManager().setComponentEnabledSetting(
                    new ComponentName(activity, PrintShareActivity.class),
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if (sStateChangeTask == this) sStateChangeTask = null;
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
開發者ID:rkshuai,項目名稱:chromium-for-android-56-debug-video,代碼行數:27,代碼來源:PrintShareActivity.java

示例10: setImageUriAsync

import android.os.AsyncTask; //導入依賴的package包/類
/**
 * Sets a bitmap loaded from the given Android URI as the content of the CropImageView.<br>
 * Can be used with URI from gallery or camera source.<br>
 * Will rotate the image by exif data.<br>
 *
 * @param uri the URI to load the image from
 */
public void setImageUriAsync(Uri uri) {
  if (uri != null) {
    BitmapLoadingWorkerTask currentTask =
        mBitmapLoadingWorkerTask != null ? mBitmapLoadingWorkerTask.get() : null;
    if (currentTask != null) {
      // cancel previous loading (no check if the same URI because camera URI can be the same for
      // different images)
      currentTask.cancel(true);
    }

    // either no existing task is working or we canceled it, need to load new URI
    clearImageInt();
    mRestoreCropWindowRect = null;
    mRestoreDegreesRotated = 0;
    mCropOverlayView.setInitialCropWindowRect(null);
    mBitmapLoadingWorkerTask = new WeakReference<>(new BitmapLoadingWorkerTask(this, uri));
    mBitmapLoadingWorkerTask.get().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    setProgressBarVisibility();
  }
}
 
開發者ID:prashantsaini1,項目名稱:android-titanium-imagecropper,代碼行數:28,代碼來源:CropImageView.java

示例11: getResponse

import android.os.AsyncTask; //導入依賴的package包/類
public static void getResponse(String input, final BotCallback<String> callback) {
    final CleverBotQuery bot = new CleverBotQuery(API_KEY, input);

    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            String response;
            try {
                bot.sendRequest();
                response = bot.getResponse();
                callback.onSuccess(response);
            } catch (IOException e) {
                response = e.getMessage();
                callback.onFailure(response);
            }
        }
    });


}
 
開發者ID:VidyaSastry,項目名稱:Opal-Chat-AnalyticsDashboard,代碼行數:21,代碼來源:BotStuff.java

示例12: configViews

import android.os.AsyncTask; //導入依賴的package包/類
@Override
public void configViews() {

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

        @Override
        protected Void doInBackground(Void... params) {
            loadBook();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            initPager();

            initTocList();
        }
    }.execute();

}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:21,代碼來源:ReadEPubActivity.java

示例13: uploadSingleRoad

import android.os.AsyncTask; //導入依賴的package包/類
public void uploadSingleRoad(final RoadModel road, final String dropboxPath,
                             final MeasurementsDataHelper.MeasurementsDataLoaderListener listener) {
    initUpload();
    //showProgress(true);
    new AsyncTask<Object, Object, Object>() {
        @Override
        protected Object doInBackground(Object[] params) {
            checkValidToken();
            long folderId = road.getFolderId();
            FolderModel folder = folderDAO.getFolder(folderId);
            checkDataDirs(dropboxPath, folder, road, DataSyncMode.ROAD);
            uploadRoad(folder, road, dropboxPath);
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            showProgress(false);
            if (listener != null) {
                listener.onDataLoaded(true);
            }
        }
    }.execute();
}
 
開發者ID:WorldBank-Transport,項目名稱:RoadLab-Pro,代碼行數:25,代碼來源:SyncDataManager.java

示例14: run

import android.os.AsyncTask; //導入依賴的package包/類
@Override
public void run(final Context context, final Callback callback) {
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... params) {
            final AbstractUserDataSyncHelper syncer = UserDataSyncHelperFactory.buildSyncHelper(
                    context, AccountUtils.getActiveAccountName(context));
            syncer.sync();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            callback.done(true, "Sync done");
        }
    }.execute(context);

}
 
開發者ID:dreaminglion,項目名稱:iosched-reader,代碼行數:19,代碼來源:ForceAppDataSyncNowAction.java

示例15: getPhotos

import android.os.AsyncTask; //導入依賴的package包/類
/**
 * Get photos from {@link MediaStore.Images}, most recent first.
 *
 * @param params a map containing the following keys:
 *        <ul>
 *          <li>first (mandatory): a number representing the number of photos to fetch</li>
 *          <li>
 *            after (optional): a cursor that matches page_info[end_cursor] returned by a
 *            previous call to {@link #getPhotos}
 *          </li>
 *          <li>groupName (optional): an album name</li>
 *          <li>
 *            mimeType (optional): restrict returned images to a specific mimetype (e.g.
 *            image/jpeg)
 *          </li>
 *        </ul>
 * @param promise the Promise to be resolved when the photos are loaded; for a format of the
 *        parameters passed to this callback, see {@code getPhotosReturnChecker} in CameraRoll.js
 */
@ReactMethod
public void getPhotos(final ReadableMap params, final Promise promise) {
  int first = params.getInt("first");
  String after = params.hasKey("after") ? params.getString("after") : null;
  String groupName = params.hasKey("groupName") ? params.getString("groupName") : null;
  ReadableArray mimeTypes = params.hasKey("mimeTypes")
      ? params.getArray("mimeTypes")
      : null;
  if (params.hasKey("groupTypes")) {
    throw new JSApplicationIllegalArgumentException("groupTypes is not supported on Android");
  }

  new GetPhotosTask(
        getReactApplicationContext(),
        first,
        after,
        groupName,
        mimeTypes,
        promise)
        .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
開發者ID:qq565999484,項目名稱:RNLearn_Project1,代碼行數:41,代碼來源:CameraRollManager.java


注:本文中的android.os.AsyncTask類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。