当前位置: 首页>>代码示例>>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;未经允许,请勿转载。