Java Code Examples for android.os.AsyncTask

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project prishlo-li-android, under directory /src/org/aectann/postage/.

Source file: AsyncTaskAwareActivity.java

  19 
vote

@SuppressWarnings("rawtypes") protected void executeTask(AsyncTask task,String... params){
  for (Iterator<AsyncTask> iterator=tasks.iterator(); iterator.hasNext(); ) {
    AsyncTask next=iterator.next();
    if (next.isCancelled() || next.getStatus() == AsyncTask.Status.FINISHED) {
      iterator.remove();
    }
  }
  tasks.add(task);
  task.execute(params);
}
 

Example 2

From project mp3tunes-android, under directory /src/com/mp3tunes/android/activity/.

Source file: Login.java

  17 
vote

/** 
 * Called when the activity is first created. 
 */
@Override public void onCreate(Bundle icicle){
  super.onCreate(icicle);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  SharedPreferences settings=getSharedPreferences(PREFS,0);
  String user=settings.getString("mp3tunes_user","");
  String pass=settings.getString("mp3tunes_pass","");
  System.out.println("user: " + user + " pass: "+ pass);
  if (!user.equals("") && !pass.equals("")) {
    AsyncTask task=new LoginTask().execute(user,pass);
    try {
      task.get();
    }
 catch (    InterruptedException e) {
      e.printStackTrace();
    }
catch (    ExecutionException e) {
      e.printStackTrace();
    }
  }
  setContentView(R.layout.login);
  mPassField=(EditText)findViewById(R.id.password);
  mUserField=(EditText)findViewById(R.id.username);
  mLoginButton=(Button)findViewById(R.id.sign_in_button);
  mPassField.setOnKeyListener(mKeyListener);
  AlertDialog.Builder builder;
  LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
  View layout=inflater.inflate(R.layout.progress_dialog,(ViewGroup)findViewById(R.id.layout_root));
  TextView text=(TextView)layout.findViewById(R.id.progress_text);
  text.setText(R.string.loading_authentication);
  builder=new AlertDialog.Builder(this);
  builder.setView(layout);
  mProgDialog=builder.create();
  if (icicle != null) {
    user=icicle.getString("username");
    pass=icicle.getString("pass");
    if (user != null)     mUserField.setText(user);
    if (pass != null)     mPassField.setText(pass);
  }
  mLoginButton.setOnClickListener(mClickListener);
}
 

Example 3

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/activity/.

Source file: SplashActivity.java

  16 
vote

@Override protected void onStart(){
  super.onStart();
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... voids){
      long startTime=System.currentTimeMillis();
      Intents.startSensors(getApplication());
      long sleepTime=sleepTime(startTime);
      sleep(sleepTime);
      return null;
    }
    private long sleepTime(    long startTime){
      long elapsed=System.currentTimeMillis() - startTime;
      return Math.max(MIN_SPLASH_TIME - elapsed,0);
    }
    private void sleep(    long sleepTime){
      try {
        Thread.sleep(sleepTime);
      }
 catch (      InterruptedException e) {
        Thread.interrupted();
      }
    }
    @Override protected void onPostExecute(    Void aVoid){
      startActivity(new Intent(getApplication(),SoundTraceActivity.class));
    }
  }
.execute();
}
 

Example 4

From project FileExplorer, under directory /src/net/micode/fileexplorer/.

Source file: FileOperationHelper.java

  16 
vote

private void asnycExecute(Runnable r){
  final Runnable _r=r;
  new AsyncTask(){
    @Override protected Object doInBackground(    Object... params){
synchronized (mCurFileNameList) {
        _r.run();
      }
      if (mOperationListener != null) {
        mOperationListener.onFinish();
      }
      return null;
    }
  }
.execute();
}
 

Example 5

From project iosched, under directory /android/src/com/google/android/apps/iosched/util/.

Source file: AnalyticsUtils.java

  16 
vote

public void trackEvent(final String category,final String action,final String label,final int value){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... voids){
      try {
        mTracker.trackEvent(category,action,label,value);
        Log.d(TAG,"iosched Analytics trackEvent: " + category + " / "+ action+ " / "+ label+ " / "+ value);
      }
 catch (      Exception e) {
        Log.w(TAG,"iosched Analytics trackEvent error: " + category + " / "+ action+ " / "+ label+ " / "+ value,e);
      }
      return null;
    }
  }
.execute();
}
 

Example 6

From project AmDroid, under directory /AmDroid/src/main/java/com/jaeckel/amenoid/fragments/.

Source file: AmenListFragment.java

  15 
vote

@Override protected void appendCachedData(){
  if (!stopAppending && (feedType != AmenService.FEED_TYPE_POPULAR)) {
    if (amenListAdapter.getCount() > 0) {
      final Long lastId=amenListAdapter.getItem(amenListAdapter.getCount() - 1).getId();
      if (endlessTask != null) {
        AsyncTask.Status status=endlessTask.getStatus();
        if (status == AsyncTask.Status.FINISHED) {
          endlessTask=new EndlessLoaderAsyncTask(getActivity());
          endlessTask.execute(lastId);
        }
      }
 else {
        endlessTask=new EndlessLoaderAsyncTask(getActivity());
        endlessTask.execute(lastId);
      }
    }
  }
}
 

Example 7

From project and-bible, under directory /AndBible/src/net/bible/android/view/activity/base/.

Source file: DocumentSelectionBase.java

  15 
vote

protected void populateMasterDocumentList(final boolean refresh){
  Log.d(TAG,"populate Master Document List");
  new AsyncTask<Void,Boolean,Void>(){
    @Override protected void onPreExecute(){
      showHourglass();
      showPreLoadMessage();
    }
    @Override protected Void doInBackground(    Void... noparam){
      try {
        allDocuments=getDocumentsFromSource(refresh);
        Log.i(TAG,"number of documents:" + allDocuments.size());
      }
 catch (      Exception e) {
        Log.e(TAG,"Error getting documents",e);
        showErrorMsg("Error getting documents");
      }
      return null;
    }
    @Override protected void onPostExecute(    Void result){
      try {
        if (allDocuments != null) {
          populateLanguageList();
          setDefaultLanguage();
          filterDocuments();
        }
      }
  finally {
        dismissHourglass();
      }
    }
  }
.execute((Void[])null);
}
 

Example 8

From project andlytics, under directory /src/com/github/andlyticsproject/util/.

Source file: Utils.java

  15 
vote

@SuppressLint("NewApi") public static <P,T extends AsyncTask<P,?,?>>void execute(T task,P... params){
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params);
  }
 else {
    task.execute(params);
  }
}
 

Example 9

From project Android, under directory /AndroidNolesCore/src/activities/.

Source file: AbstractMainActivity.java

  15 
vote

@Override protected void onCreate(Bundle savedInstanceState){
  final boolean SUPPORTS_GINGERBREAD=Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
  if (BuildConfig.DEBUG && SUPPORTS_GINGERBREAD) {
    StrictMode.enableDefaults();
  }
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  final AsyncTask<Void,Void,Void> enableCache=new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... urls){
      enableHttpResponseCache();
      return null;
    }
  }
;
  enableCache.execute();
  mViewPager=(ViewPager)findViewById(R.id.pager);
}
 

Example 10

From project android-client_2, under directory /src/org/mifos/androidclient/main/.

Source file: AccountDetailsActivity.java

  15 
vote

private void runAccountDetailsTask(){
  if (mAccount == null || !StringUtils.hasLength(mAccount.getGlobalAccountNum())) {
    mUIUtils.displayLongMessage(getString(R.string.toast_customer_id_not_available));
    return;
  }
  if (mAccountDetailsTask == null || mAccountDetailsTask.getStatus() != AsyncTask.Status.RUNNING) {
    mAccountDetailsTask=new AccountDetailsTask(this,getString(R.string.dialog_getting_account_data),getString(R.string.dialog_loading_message));
    mAccountDetailsTask.execute(mAccount);
  }
}
 

Example 11

From project Android-FFXIEQ, under directory /ffxieq/src/com/github/kanata3249/ffxieq/android/.

Source file: CharacterStatusView.java

  15 
vote

public boolean cacheStatusAsync(){
  if (mCharInfo.isCacheValid() && (mCharInfoToCompare == null || mCharInfoToCompare.isCacheValid()))   return false;
  final ProgressBar progress=(ProgressBar)findViewById(R.id.ProgressBar);
  if (progress != null) {
    progress.setVisibility(VISIBLE);
  }
  AsyncTask<Void,Void,Void> task=new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... params){
synchronized (sObjLock) {
        mCharInfo.cacheStatusValues();
        if (mCharInfoToCompare != null)         mCharInfoToCompare.cacheStatusValues();
      }
      return null;
    }
    @Override protected void onPostExecute(    Void result){
      notifyDatasetChanged();
      if (progress != null)       progress.setVisibility(INVISIBLE);
    }
  }
;
  task.execute();
  return true;
}
 

Example 12

From project android-marvin, under directory /marvin-it/src/test/android/de/akquinet/android/marvintest/activities/.

Source file: ActivityA.java

  15 
vote

@Override protected void onResume(){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... params){
      TestUtils.sleepQuietly(1000);
      return null;
    }
    protected void onPostExecute(    Void result){
      Intent intent=new Intent(ActivityA.this,ActivityB.class);
      startActivity(intent);
    }
  }
.execute();
  super.onResume();
}
 

Example 13

From project android-sdk, under directory /src/main/java/com/mobeelizer/mobile/android/.

Source file: MobeelizerApplication.java

  15 
vote

public void login(final String instance,final String user,final String password,final MobeelizerOperationCallback callback){
  new AsyncTask<Void,Void,MobeelizerOperationError>(){
    @Override protected MobeelizerOperationError doInBackground(    final Void... params){
      return login(instance,user,password);
    }
    @Override protected void onPostExecute(    final MobeelizerOperationError error){
      super.onPostExecute(error);
      if (error == null) {
        callback.onSuccess();
      }
 else {
        callback.onFailure(error);
      }
    }
  }
.execute();
}
 

Example 14

From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/core/activity/.

Source file: TopLevelActivity.java

  15 
vote

@Override protected void onDestroy(){
  super.onDestroy();
  if (mTask != null && mTask.getStatus() != AsyncTask.Status.RUNNING) {
    mTask.cancel(true);
  }
}
 

Example 15

From project android-thaiime, under directory /latinime/src/com/android/inputmethod/deprecated/.

Source file: VoiceProxy.java

  15 
vote

private void switchToLastInputMethod(){
  if (!VOICE_INSTALLED) {
    return;
  }
  final IBinder token=mService.getWindow().getWindow().getAttributes().token;
  new AsyncTask<Void,Void,Boolean>(){
    @Override protected Boolean doInBackground(    Void... params){
      return mImm.switchToLastInputMethod(token);
    }
    @Override protected void onPostExecute(    Boolean result){
      if (!result) {
        if (DEBUG) {
          Log.d(TAG,"Couldn't switch back to last IME.");
        }
        mVoiceInput.reset();
        mService.requestHideSelf(0);
      }
 else {
        mService.notifyOnCurrentInputMethodSubtypeChanged(null);
      }
    }
  }
.execute();
}
 

Example 16

From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/widget/.

Source file: SettingsAppWidgetProvider.java

  15 
vote

@Override protected void requestStateChange(Context context,final boolean desiredState){
  final WifiManager wifiManager=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
  if (wifiManager == null) {
    Log.d(TAG,"No wifiManager.");
    return;
  }
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... args){
      int wifiApState=wifiManager.getWifiApState();
      if (desiredState && ((wifiApState == WifiManager.WIFI_AP_STATE_ENABLING) || (wifiApState == WifiManager.WIFI_AP_STATE_ENABLED))) {
        wifiManager.setWifiApEnabled(null,false);
      }
      wifiManager.setWifiEnabled(desiredState);
      return null;
    }
  }
.execute();
}
 

Example 17

From project android_packages_apps_Tag, under directory /src/com/android/apps/tag/provider/.

Source file: TagProvider.java

  15 
vote

/** 
 * A helper function for implementing  {@link #openFile}, for creating a data pipe and background thread allowing you to stream generated data back to the client.  This function returns a new ParcelFileDescriptor that should be returned to the caller (the caller is responsible for closing it).
 * @param uri The URI whose data is to be written.
 * @param func Interface implementing the function that will actuallystream the data.
 * @return Returns a new ParcelFileDescriptor holding the read side ofthe pipe.  This should be returned to the caller for reading; the caller is responsible for closing it when done.
 */
public ParcelFileDescriptor openMimePipe(final Uri uri,final TagProviderPipeDataWriter func) throws FileNotFoundException {
  try {
    final ParcelFileDescriptor[] fds=ParcelFileDescriptor.createPipe();
    AsyncTask<Object,Object,Object> task=new AsyncTask<Object,Object,Object>(){
      @Override protected Object doInBackground(      Object... params){
        func.writeMimeDataToPipe(fds[1],uri);
        try {
          fds[1].close();
        }
 catch (        IOException e) {
          Log.w(TAG,"Failure closing pipe",e);
        }
        return null;
      }
    }
;
    task.execute((Object[])null);
    return fds[0];
  }
 catch (  IOException e) {
    throw new FileNotFoundException("failure making pipe");
  }
}
 

Example 18

From project android_packages_apps_TouchWiz30Launcher, under directory /src/com/sec/android/app/twlauncher/.

Source file: LiveFolder.java

  15 
vote

void bind(FolderInfo folderinfo){
  super.bind(folderinfo);
  if (mLoadingTask != null && mLoadingTask.getStatus() == android.os.AsyncTask.Status.RUNNING)   mLoadingTask.cancel(true);
  FolderLoadingTask folderloadingtask=new FolderLoadingTask(this);
  LiveFolderInfo alivefolderinfo[]=new LiveFolderInfo[1];
  alivefolderinfo[0]=(LiveFolderInfo)folderinfo;
  mLoadingTask=folderloadingtask.execute(alivefolderinfo);
}
 

Example 19

From project android_packages_inputmethods_LatinIME, under directory /java/src/com/android/inputmethod/deprecated/.

Source file: VoiceProxy.java

  15 
vote

private void switchToLastInputMethod(){
  if (!VOICE_INSTALLED) {
    return;
  }
  final IBinder token=mService.getWindow().getWindow().getAttributes().token;
  new AsyncTask<Void,Void,Boolean>(){
    @Override protected Boolean doInBackground(    Void... params){
      return mImm.switchToLastInputMethod(token);
    }
    @Override protected void onPostExecute(    Boolean result){
      if (!result) {
        if (DEBUG) {
          Log.d(TAG,"Couldn't switch back to last IME.");
        }
        mVoiceInput.reset();
        mService.requestHideSelf(0);
      }
 else {
        mService.notifyOnCurrentInputMethodSubtypeChanged(null);
      }
    }
  }
.execute();
}
 

Example 20

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: DeckTask.java

  15 
vote

/** 
 * Block the current thread until the currently running DeckTask instance (if any) has finished.
 */
public static void waitToFinish(){
  try {
    if ((sInstance != null) && (sInstance.getStatus() != AsyncTask.Status.FINISHED)) {
      sInstance.get();
    }
  }
 catch (  Exception e) {
    return;
  }
}
 

Example 21

From project AnySoftKeyboard, under directory /src/com/anysoftkeyboard/dictionaries/.

Source file: ContactsDictionary.java

  15 
vote

public ContactsDictionary(Context context) throws Exception {
  super("ContactsDictionary",context);
  ContentResolver cres=mContext.getContentResolver();
  cres.registerContentObserver(Contacts.CONTENT_URI,true,mObserver=new ContentObserver(null){
    @Override public void onChange(    boolean self){
      if (AnyApplication.DEBUG)       Log.d(TAG,"Contacts list modified (self: " + self + "). Reloading...");
      new AsyncTask<Void,Void,Void>(){
        @Override protected Void doInBackground(        Void... params){
          loadDictionaryAsync();
          return null;
        }
      }
.execute();
    }
  }
);
}
 

Example 22

From project AquaNotesTest, under directory /src/com/google/android/apps/iosched/util/.

Source file: AnalyticsUtils.java

  15 
vote

public void trackEvent(final String category,final String action,final String label,final int value){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... voids){
      try {
        mTracker.trackEvent(category,action,label,value);
        Log.d(TAG,"iosched Analytics trackEvent: " + category + " / "+ action+ " / "+ label+ " / "+ value);
      }
 catch (      Exception e) {
        Log.w(TAG,"iosched Analytics trackEvent error: " + category + " / "+ action+ " / "+ label+ " / "+ value,e);
      }
      return null;
    }
  }
.execute();
}
 

Example 23

From project BazaarUtils, under directory /src/com/congenialmobile/widget/.

Source file: LazyImageView.java

  15 
vote

protected AsyncTask<Void,Void,Void> getFetcher(){
  return (new AsyncTask<Void,Void,Void>(){
    @Override public Void doInBackground(    Void... nothing){
      if (stop || (cacheFile == null) || isDownloading)       return null;
      isDownloading=true;
      stopperIndicator.reuse();
      isDownloaded=NetUtils.retrieveAndSave(imageUrl,cacheFile,stopperIndicator);
      if (DEBUG_LIV)       Log.d(TAG,"LazyImageView :: isDownloaded=" + isDownloaded + ", url="+ imageUrl);
      if (isDownloaded)       handler.post(onDownloaded);
      isDownloading=false;
      return null;
    }
  }
);
}
 

Example 24

From project conference-mobile-app, under directory /android-app/src/com/google/android/apps/iosched/util/.

Source file: AnalyticsUtils.java

  15 
vote

public void trackEvent(final String category,final String action,final String label,final int value){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... voids){
      try {
        mTracker.trackEvent(category,action,label,value);
        Log.d(TAG,"iosched Analytics trackEvent: " + category + " / "+ action+ " / "+ label+ " / "+ value);
      }
 catch (      Exception e) {
        Log.w(TAG,"iosched Analytics trackEvent error: " + category + " / "+ action+ " / "+ label+ " / "+ value,e);
      }
      return null;
    }
  }
.execute();
}
 

Example 25

From project creamed_glacier_app_settings, under directory /src/com/android/settings/.

Source file: DataUsageSummary.java

  15 
vote

@Override public void onResume(){
  super.onResume();
  final Intent intent=getActivity().getIntent();
  mIntentTab=computeTabFromIntent(intent);
  updateTabs();
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... params){
      try {
        Thread.sleep(2 * DateUtils.SECOND_IN_MILLIS);
        mStatsService.forceUpdate();
      }
 catch (      InterruptedException e) {
      }
catch (      RemoteException e) {
      }
      return null;
    }
    @Override protected void onPostExecute(    Void result){
      if (isAdded()) {
        updateBody();
      }
    }
  }
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 

Example 26

From project Cura, under directory /src/com/cura/.

Source file: CuraActivity.java

  15 
vote

public void initServerInfo(){
  new AsyncTask<String,String,String>(){
    @Override protected void onPreExecute(){
      super.onPreExecute();
      loader_message=getString(R.string.initializing);
    }
    @Override protected String doInBackground(    String... arg0){
      while (connectionTrigger) {
        if (conn != null) {
          uptime=getUptime();
          uname=getUname();
          location=getLocation();
          connectionTrigger=false;
        }
      }
      return null;
    }
    @Override protected void onPostExecute(    String result){
      super.onPostExecute(result);
    }
  }
.execute();
}
 

Example 27

From project cw-omnibus, under directory /EmPubLite/T12-Book/src/com/commonsware/empublite/.

Source file: ModelFragment.java

  15 
vote

@TargetApi(11) static public <T>void executeAsyncTask(AsyncTask<T,?,?> task,T... params){
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params);
  }
 else {
    task.execute(params);
  }
}
 

Example 28

From project dcnyc10-android, under directory /android/src/com/lullabot/android/apps/iosched/util/.

Source file: AnalyticsUtils.java

  15 
vote

public void trackEvent(final String category,final String action,final String label,final int value){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... voids){
      try {
        mTracker.trackEvent(category,action,label,value);
        Log.d(TAG,"iosched Analytics trackEvent: " + category + " / "+ action+ " / "+ label+ " / "+ value);
      }
 catch (      Exception e) {
        Log.w(TAG,"iosched Analytics trackEvent error: " + category + " / "+ action+ " / "+ label+ " / "+ value,e);
      }
      return null;
    }
  }
.execute();
}
 

Example 29

From project devoxx-france-android-in-fine, under directory /src/com/infine/android/devoxx/util/.

Source file: AnalyticsUtils.java

  15 
vote

public void trackEvent(final String category,final String action,final String label,final int value){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... voids){
      try {
        mTracker.trackEvent(category,action,label,value);
        Log.d(TAG,"Infine Analytics trackEvent: " + category + " / "+ action+ " / "+ label+ " / "+ value);
      }
 catch (      Exception e) {
        Log.w(TAG,"Infine Analytics trackEvent error: " + category + " / "+ action+ " / "+ label+ " / "+ value,e);
      }
      return null;
    }
  }
.execute();
}
 

Example 30

From project dreamDroid, under directory /src/net/reichholf/dreamdroid/fragment/.

Source file: ScreenShotFragment.java

  15 
vote

private void cancelTaskIfRunning(){
  if (mGetScreenshotTask != null) {
    if (mGetScreenshotTask.getStatus().equals(AsyncTask.Status.RUNNING)) {
      mGetScreenshotTask.cancel(true);
    }
  }
}
 

Example 31

From project droidkit, under directory /src/org/droidkit/net/ezhttp/.

Source file: EzHttpRequest.java

  15 
vote

public void executeAsync(){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... params){
      executeInSync();
      return null;
    }
  }
.execute((Void)null);
}
 

Example 32

From project ElectricSleep, under directory /src/com/androsz/electricsleepbeta/alarmclock/.

Source file: AlarmAlertFullScreen.java

  15 
vote

private void snooze(){
  if (!findViewById(R.id.snooze).isEnabled()) {
    dismiss(false);
    return;
  }
  new AsyncTask<Void,Void,Integer>(){
    final Calendar c=Calendar.getInstance();
    @Override protected Integer doInBackground(    Void... params){
      final String snooze=getSharedPreferences(SettingsActivity.PREFERENCES,0).getString(SettingsActivity.KEY_ALARM_SNOOZE,DEFAULT_SNOOZE);
      final int snoozeMinutes=Integer.parseInt(snooze);
      final long snoozeTime=System.currentTimeMillis() + 1000 * 60 * snoozeMinutes;
      Alarms.saveSnoozeAlert(AlarmAlertFullScreen.this,mAlarm.id,snoozeTime);
      c.setTimeInMillis(snoozeTime);
      return snoozeMinutes;
    }
    @Override protected void onPostExecute(    Integer snoozeMinutes){
      String label=mAlarm.getLabelOrDefault(AlarmAlertFullScreen.this);
      label=getString(R.string.alarm_notify_snooze_label,label);
      final Intent cancelSnooze=new Intent(AlarmAlertFullScreen.this,AlarmReceiver.class);
      cancelSnooze.setAction(Alarms.CANCEL_SNOOZE);
      cancelSnooze.putExtra(Alarms.ALARM_ID,mAlarm.id);
      final PendingIntent broadcast=PendingIntent.getBroadcast(AlarmAlertFullScreen.this,mAlarm.id,cancelSnooze,0);
      final NotificationManager nm=getNotificationManager();
      final Notification n=new Notification(R.drawable.ic_alarm_neutral,label,0);
      n.setLatestEventInfo(AlarmAlertFullScreen.this,label,getString(R.string.alarm_notify_snooze_text,Alarms.formatTime(AlarmAlertFullScreen.this,c)),broadcast);
      n.flags|=Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONGOING_EVENT;
      nm.notify(mAlarm.id,n);
      final String displayTime=getString(R.string.alarm_alert_snooze_set,snoozeMinutes);
      Log.v(displayTime);
      Toast.makeText(AlarmAlertFullScreen.this,displayTime,Toast.LENGTH_LONG).show();
      stopService(new Intent(Alarms.ALARM_ALERT_ACTION));
      finish();
    }
  }
.execute();
}
 

Example 33

From project empub, under directory /src/com/commonsware/empub/.

Source file: ModelFragment.java

  15 
vote

@TargetApi(11) static public <T>void executeAsyncTask(AsyncTask<T,?,?> task,T... params){
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params);
  }
 else {
    task.execute(params);
  }
}
 

Example 34

From project gast-lib, under directory /app/src/root/gast/playground/audio/.

Source file: ClapperPlay.java

  15 
vote

private void shutDownTaskIfNecessary(final AsyncTask task){
  if ((task != null) && (!task.isCancelled())) {
    if ((task.getStatus().equals(AsyncTask.Status.RUNNING)) || (task.getStatus().equals(AsyncTask.Status.PENDING))) {
      Log.d(TAG,"CANCEL " + task.getClass().getSimpleName());
      task.cancel(true);
    }
 else {
      Log.d(TAG,"task not running");
    }
  }
}
 

Example 35

From project GCM-Demo, under directory /gcm/samples/gcm-demo-client/src/com/google/android/gcm/demo/app/.

Source file: DemoActivity.java

  15 
vote

@Override public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  checkNotNull(SERVER_URL,"SERVER_URL");
  checkNotNull(SENDER_ID,"695223804692");
  GCMRegistrar.checkDevice(this);
  GCMRegistrar.checkManifest(this);
  setContentView(R.layout.main);
  mDisplay=(TextView)findViewById(R.id.display);
  registerReceiver(mHandleMessageReceiver,new IntentFilter(DISPLAY_MESSAGE_ACTION));
  final String regId=GCMRegistrar.getRegistrationId(this);
  if (regId.equals("")) {
    GCMRegistrar.register(this,SENDER_ID);
  }
 else {
    if (GCMRegistrar.isRegisteredOnServer(this)) {
      mDisplay.append(getString(R.string.already_registered) + "\n");
    }
 else {
      final Context context=this;
      mRegisterTask=new AsyncTask<Void,Void,Void>(){
        @Override protected Void doInBackground(        Void... params){
          boolean registered=ServerUtilities.register(context,regId);
          if (!registered) {
            GCMRegistrar.unregister(context);
          }
          return null;
        }
        @Override protected void onPostExecute(        Void result){
          mRegisterTask=null;
        }
      }
;
      mRegisterTask.execute(null,null,null);
    }
  }
}
 

Example 36

From project gddsched2, under directory /trunk/android/src/com/google/android/apps/iosched2/util/.

Source file: AnalyticsUtils.java

  15 
vote

public void trackEvent(final String category,final String action,final String label,final int value){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... voids){
      try {
        mTracker.trackEvent(category,action,label,value);
        Log.d(TAG,"gddsched Analytics trackEvent: " + category + " / "+ action+ " / "+ label+ " / "+ value);
      }
 catch (      Exception e) {
        Log.w(TAG,"gddsched Analytics trackEvent error: " + category + " / "+ action+ " / "+ label+ " / "+ value,e);
      }
      return null;
    }
  }
.execute();
}
 

Example 37

From project GeekAlarm, under directory /android/src/com/geek_alarm/android/activities/.

Source file: TaskActivity.java

  15 
vote

@Override public void onClick(View v){
  all++;
  solved+=v.getId() == correctChoiceId ? 1 : 0;
  new ResultSender(currentTask.getId(),v.getId() == correctChoiceId).execute();
  if (2 * solved - all == positiveBalance || all == numberOfAttempts) {
    boolean win=2 * solved - all == positiveBalance;
    if (!testTask) {
      Intent intent=new Intent(TaskActivity.this,ResultActivity.class);
      intent.putExtra("win",win);
      intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
      startActivity(intent);
    }
    TaskActivity.this.finish();
    return;
  }
  layout.removeViewAt(layout.getChildCount() - 1);
  updateStats();
  Toast.makeText(getApplicationContext(),v.getId() == correctChoiceId ? "Accepted" : "Wrong answer",Toast.LENGTH_SHORT).show();
  if (availableTasks.isEmpty()) {
    if (loader.getStatus() == AsyncTask.Status.FINISHED) {
      loader=new TaskLoader();
      loader.execute();
    }
    waitingForTask=true;
    toggleSpinner(true);
  }
 else {
    displayTask(availableTasks.poll());
  }
}
 

Example 38

From project gmarks-android, under directory /src/main/java/org/thomnichols/android/gmarks/.

Source file: ListsListActivity.java

  15 
vote

protected void doListSync(){
  Toast.makeText(this,R.string.sync_begin_msg,Toast.LENGTH_SHORT).show();
  final ListActivity ctx=this;
  new AsyncTask<Void,Integer,Integer>(){
    @Override protected Integer doInBackground(    Void... params){
      Log.d(TAG,"Starting list sync...");
      ListsSync sync=new ListsSync(ctx);
      DatabaseHelper db=new DatabaseHelper(ctx);
      try {
        sync.synchronizeMyLists(db);
        ((CursorAdapter)ctx.getListAdapter()).getCursor().requery();
      }
 catch (      AuthException ex) {
        Log.w(TAG,"Auth failure",ex);
        return SYNC_RESULT_AUTH_ERR;
      }
catch (      Exception ex) {
        Log.w(TAG,"Lists sync error",ex);
        return SYNC_RESULT_ERROR;
      }
      return SYNC_RESULT_OK;
    }
    protected void onPostExecute(    Integer result){
      int msgID=R.string.sync_done_msg;
      if (result == SYNC_RESULT_AUTH_ERR) {
        msgID=R.string.sync_notify_auth_error;
        startActivity(new Intent(ctx,WebViewLoginActivity.class));
      }
 else       if (result == SYNC_RESULT_ERROR)       msgID=R.string.sync_notify_error;
      Toast.makeText(ctx,msgID,Toast.LENGTH_LONG);
    }
  }
.execute();
}
 

Example 39

From project gobandroid, under directory /src/org/ligi/gobandroid_hd/ui/tsumego/fetch/.

Source file: DownloadProblemsDialog.java

  15 
vote

public static AsyncTask<TsumegoSource[],String,Integer> getAndRunTask(GobandroidFragmentActivity activity,Refreshable refreshable){
  EasyTracker.getTracker().trackEvent("ui_action","tsumego","refresh",null);
  AsyncTask<TsumegoSource[],String,Integer> res=new DownloadProblemsDialogTask(activity,refreshable);
  res.execute(TsumegoDownloadHelper.getDefaultList(activity.getApp()));
  return res;
}
 

Example 40

From project groundhog-reader, under directory /src/main/java/com/almarsoft/GroundhogReader/.

Source file: GroupListActivity.java

  15 
vote

private void expireReadMessages(boolean expireAll){
  AsyncTask<Boolean,Void,Void> readExpirerTask=new AsyncTask<Boolean,Void,Void>(){
    @Override protected Void doInBackground(    Boolean... args){
      boolean expireAll=args[0];
      long expireTime=new Long(mPrefs.getString("expireMode","86400000")).longValue();
      DBUtils.expireReadMessages(mContext,expireAll,expireTime);
      return null;
    }
    protected void onPostExecute(    Void arg0){
      Editor ed=mPrefs.edit();
      ed.putLong("lastExpiration",System.currentTimeMillis());
      ed.commit();
      updateGroupList();
      try {
        dismissDialog(ID_DIALOG_DELETING);
      }
 catch (      IllegalArgumentException e) {
      }
    }
  }
;
  showDialog(ID_DIALOG_DELETING);
  readExpirerTask.execute(expireAll);
}
 

Example 41

From project HapiPodcastJ, under directory /src/info/xuluan/podcast/.

Source file: SearchActivity.java

  15 
vote

private void start_search(String search_url){
  SearchActivity.this.progress=ProgressDialog.show(SearchActivity.this,getResources().getText(R.string.dialog_title_loading),getResources().getText(R.string.dialog_message_loading),true);
  AsyncTask<String,ProgressDialog,String> asyncTask=new AsyncTask<String,ProgressDialog,String>(){
    String url;
    @Override protected String doInBackground(    String... params){
      url=params[0];
      return fetchChannelInfo(url);
    }
    @Override protected void onPostExecute(    String result){
      if (SearchActivity.this.progress != null) {
        SearchActivity.this.progress.dismiss();
        SearchActivity.this.progress=null;
      }
      if (result == null) {
        Toast.makeText(SearchActivity.this,getResources().getString(R.string.network_fail),Toast.LENGTH_SHORT).show();
      }
 else {
        List<SearchItem> items=parseResult(result);
        if (items.size() == 0) {
          Toast.makeText(SearchActivity.this,getResources().getString(R.string.no_data_found),Toast.LENGTH_SHORT).show();
        }
 else {
          mStart+=items.size();
          for (int i=0; i < items.size(); i++) {
            mItems.add(items.get(i));
            mAdapter.add(items.get(i).title);
          }
        }
      }
      updateBtn();
    }
  }
;
  asyncTask.execute(search_url);
}
 

Example 42

From project HeLauncher, under directory /src/com/handlerexploit/launcher_reloaded/.

Source file: LiveFolder.java

  15 
vote

void bind(FolderInfo info){
  super.bind(info);
  if (mLoadingTask != null && mLoadingTask.getStatus() == AsyncTask.Status.RUNNING) {
    mLoadingTask.cancel(true);
  }
  mLoadingTask=new FolderLoadingTask(this).execute((LiveFolderInfo)info);
}
 

Example 43

From project hsDroid, under directory /src/de/nware/app/hsDroid/ui/.

Source file: GradesList.java

  15 
vote

@Override protected void onPause(){
  super.onPause();
  Log.d(TAG,"pause... try to kill running threads");
  if (updateThread != null && updateThread.getStatus() != AsyncTask.Status.FINISHED) {
    updateThread.cancel(true);
  }
  if (mExamInfoThread != null && mExamInfoThread.getStatus() != AsyncTask.Status.FINISHED) {
    mExamInfoThread.cancel(true);
  }
}
 

Example 44

From project ICS_LatinIME_QHD, under directory /java/src/com/android/inputmethod/deprecated/.

Source file: VoiceProxy.java

  15 
vote

private void switchToLastInputMethod(){
  if (!VOICE_INSTALLED) {
    return;
  }
  final IBinder token=mService.getWindow().getWindow().getAttributes().token;
  new AsyncTask<Void,Void,Boolean>(){
    @Override protected Boolean doInBackground(    Void... params){
      return mImm.switchToLastInputMethod(token);
    }
    @Override protected void onPostExecute(    Boolean result){
      if (!result) {
        if (DEBUG) {
          Log.d(TAG,"Couldn't switch back to last IME.");
        }
        mVoiceInput.reset();
        mService.requestHideSelf(0);
      }
 else {
        mService.notifyOnCurrentInputMethodSubtypeChanged(null);
      }
    }
  }
.execute();
}
 

Example 45

From project iosched2011, under directory /android/src/com/google/android/apps/iosched/util/.

Source file: AnalyticsUtils.java

  15 
vote

public void trackEvent(final String category,final String action,final String label,final int value){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... voids){
      try {
        mTracker.trackEvent(category,action,label,value);
        Log.d(TAG,"iosched Analytics trackEvent: " + category + " / "+ action+ " / "+ label+ " / "+ value);
      }
 catch (      Exception e) {
        Log.w(TAG,"iosched Analytics trackEvent error: " + category + " / "+ action+ " / "+ label+ " / "+ value,e);
      }
      return null;
    }
  }
.execute();
}
 

Example 46

From project iosched_2, under directory /android/src/com/google/android/apps/iosched/util/.

Source file: AnalyticsUtils.java

  15 
vote

public void trackEvent(final String category,final String action,final String label,final int value){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... voids){
      try {
        mTracker.trackEvent(category,action,label,value);
        Log.d(TAG,"iosched Analytics trackEvent: " + category + " / "+ action+ " / "+ label+ " / "+ value);
      }
 catch (      Exception e) {
        Log.w(TAG,"iosched Analytics trackEvent error: " + category + " / "+ action+ " / "+ label+ " / "+ value,e);
      }
      return null;
    }
  }
.execute();
}
 

Example 47

From project iosched_3, under directory /android/src/com/google/android/apps/iosched/ui/.

Source file: HomeActivity.java

  15 
vote

private void registerGCMClient(){
  GCMRegistrar.checkDevice(this);
  if (BuildConfig.DEBUG) {
    GCMRegistrar.checkManifest(this);
  }
  final String regId=GCMRegistrar.getRegistrationId(this);
  if (TextUtils.isEmpty(regId)) {
    GCMRegistrar.register(this,Config.GCM_SENDER_ID);
  }
 else {
    if (GCMRegistrar.isRegisteredOnServer(this)) {
      LOGI(TAG,"Already registered on the GCM server");
    }
    mGCMRegisterTask=new AsyncTask<Void,Void,Void>(){
      @Override protected Void doInBackground(      Void... params){
        boolean registered=ServerUtilities.register(HomeActivity.this,regId);
        if (!registered) {
          GCMRegistrar.unregister(HomeActivity.this);
        }
        return null;
      }
      @Override protected void onPostExecute(      Void result){
        mGCMRegisterTask=null;
      }
    }
;
    mGCMRegisterTask.execute(null,null,null);
  }
}
 

Example 48

From project janbanery, under directory /janbanery-android/src/main/java/pl/project13/janbanery/android/rest/.

Source file: AndroidCompatibleRestClient.java

  15 
vote

@SuppressWarnings("unchecked") public T get(int callTimeoutSeconds){
  T result=null;
  try {
    result=new AsyncTask<Void,Void,T>(){
      @Override protected T doInBackground(      Void... voids){
        return SimpleAsyncTask.this.execute();
      }
      @Override protected void onPostExecute(      T t){
        if (throwLater != null) {
          throw new RuntimeException("Exception was thrown while fetching resource.",throwLater);
        }
      }
    }
.execute().get(callTimeoutSeconds,TimeUnit.SECONDS);
  }
 catch (  InterruptedException e) {
    Log.e(TAG,"InterruptedException while SimpleAsyncTask get()...\n" + e.toString());
  }
catch (  ExecutionException e) {
    Log.e(TAG,"ExecutionException while SimpleAsyncTask get()...\n" + e.toString());
  }
catch (  TimeoutException e) {
    Log.e(TAG,"ExecutionException while SimpleAsyncTask get()...\n" + e.toString());
  }
  return result;
}
 

Example 49

From project Juggernaut_SystemUI, under directory /src/com/android/systemui/statusbar/powerwidget/.

Source file: BluetoothButton.java

  15 
vote

@Override protected void requestStateChange(Context context,final boolean desiredState){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... args){
      BluetoothAdapter mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
      if (mBluetoothAdapter.isEnabled()) {
        mBluetoothAdapter.disable();
      }
 else {
        mBluetoothAdapter.enable();
      }
      return null;
    }
  }
.execute();
}
 

Example 50

From project k-9, under directory /src/com/fsck/k9/fragment/.

Source file: MessageViewFragment.java

  15 
vote

private void onToggleColors(){
  if (K9.getK9MessageViewTheme() == K9.THEME_DARK) {
    K9.setK9MessageViewTheme(K9.THEME_LIGHT);
  }
 else {
    K9.setK9MessageViewTheme(K9.THEME_DARK);
  }
  new AsyncTask<Object,Object,Object>(){
    @Override protected Object doInBackground(    Object... params){
      Context appContext=getActivity().getApplicationContext();
      Preferences prefs=Preferences.getPreferences(appContext);
      Editor editor=prefs.getPreferences().edit();
      K9.save(editor);
      editor.commit();
      return null;
    }
  }
.execute();
  mFragmentListener.restartActivity();
}
 

Example 51

From project LoL-Chat, under directory /src/com/rei/lolchat/ui/.

Source file: LoginAnim.java

  15 
vote

@Override protected void onStop(){
  super.onStop();
  if (mBinded && mTask.getStatus() != AsyncTask.Status.RUNNING) {
    unbindService(mServConn);
    mXmppFacade=null;
  }
}
 

Example 52

From project MicDroid, under directory /src/com/intervigil/micdroid/.

Source file: RecordingLibrary.java

  15 
vote

private void onCancelLoadRecordings(){
  if (loadRecordingsTask != null && loadRecordingsTask.getStatus() == AsyncTask.Status.RUNNING) {
    loadRecordingsTask.cancel(true);
    loadRecordingsTask=null;
  }
}
 

Example 53

From project MyExpenses, under directory /src/org/totschnig/myexpenses/.

Source file: GrisbiImport.java

  15 
vote

/** 
 * @param is InputStream to be analyzed
 * @return if there is a problem success is set to false and message to a diagnostic message (as an R string integer)if the analysis succeeds, success is true, message is 0, and extras has as first element the CategoryTree, and as second element a string array with payees DOM and SAX implementations are mainly functionally equivalent, with the main difference that the DOM implementation crashes with OutOfMemoryError on big input files the DOM implementation reports parse_error_grisbi_version_not_determined, if the XML file is unrelated to Grisbi, while the SAX implementation reports success and returns empty category tree and payee list
 */
@Override public void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);
  mProgressDialog=new ProgressDialog(this);
  mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  mProgressDialog.setProgress(0);
  mProgressDialog.setCancelable(false);
  mSourcesDialog=new AlertDialog.Builder(this).setTitle(R.string.dialog_title_select_import_source).setCancelable(false).setSingleChoiceItems(IMPORT_SOURCES,-1,this).setNegativeButton(R.string.button_cancel,this).setNeutralButton(R.string.grisbi_import_button_categories_only,this).setPositiveButton(R.string.grisbi_import_button_categories_and_parties,this).create();
  task=(MyAsyncTask)getLastNonConfigurationInstance();
  if (task != null) {
    task.attach(this);
    sourceIndex=task.getSource();
    mProgressDialog.setTitle(task.getTitle());
    mProgressDialog.setMax(task.getMax());
    mProgressDialog.show();
    updateProgress(task.getProgress());
    if (task.getStatus() == AsyncTask.Status.FINISHED) {
      markAsDone();
    }
  }
 else   if (savedInstanceState == null) {
    showDialog(SOURCES_DIALOG_ID);
    mSourcesDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    mSourcesDialog.getButton(AlertDialog.BUTTON_NEUTRAL).setEnabled(false);
  }
}
 

Example 54

From project NFC-Contact-Exchanger, under directory /src/com/tonchidot/nfc_contact_exchanger/.

Source file: ContacterMainActivity.java

  15 
vote

private void handlePictureUpload(){
  new AsyncTask<Void,Void,String>(){
    @Override protected String doInBackground(    Void... params){
      byte[] pictureData=VCardUtils.getPictureData(selectedVcardString);
      String url=null;
      if (pictureData != null) {
        PictureUploader uploader=new PictureUploader();
        url=uploader.uploadPicture(pictureData);
      }
      return url;
    }
    @Override protected void onPostExecute(    String url){
      preferences.savePhotoOnlineUrl(url);
      try {
        setUpForgroundNdefPush();
      }
 catch (      Exception e) {
      }
    }
  }
.execute();
}
 

Example 55

From project Notes, under directory /src/net/micode/notes/ui/.

Source file: NotesListActivity.java

  15 
vote

private void batchDelete(){
  new AsyncTask<Void,Void,HashSet<AppWidgetAttribute>>(){
    protected HashSet<AppWidgetAttribute> doInBackground(    Void... unused){
      HashSet<AppWidgetAttribute> widgets=mNotesListAdapter.getSelectedWidget();
      if (!isSyncMode()) {
        if (DataUtils.batchDeleteNotes(mContentResolver,mNotesListAdapter.getSelectedItemIds())) {
        }
 else {
          Log.e(TAG,"Delete notes error, should not happens");
        }
      }
 else {
        if (!DataUtils.batchMoveToFolder(mContentResolver,mNotesListAdapter.getSelectedItemIds(),Notes.ID_TRASH_FOLER)) {
          Log.e(TAG,"Move notes to trash folder error, should not happens");
        }
      }
      return widgets;
    }
    @Override protected void onPostExecute(    HashSet<AppWidgetAttribute> widgets){
      if (widgets != null) {
        for (        AppWidgetAttribute widget : widgets) {
          if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
            updateWidget(widget.widgetId,widget.widgetType);
          }
        }
      }
      mModeCallBack.finishActionMode();
    }
  }
.execute();
}
 

Example 56

From project ohmagePhone, under directory /src/org/ohmage/.

Source file: AccountHelper.java

  15 
vote

/** 
 * 1) Clears the user's data, 2) redirects the user to the login page, and 3) clears the backstack + makes it a new task, so they can't get back into the app
 */
private void clearAndGotoLogin(){
  AsyncTask<Void,Void,Void> wipeTask=new AsyncTask<Void,Void,Void>(){
    @Override protected void onPreExecute(){
      super.onPreExecute();
      mActivity.showDialog(DIALOG_WIPE_PROGRESS);
    }
    @Override protected Void doInBackground(    Void... params){
      ((OhmageApplication)mActivity.getApplication()).resetAll();
      return null;
    }
    @Override protected void onPostExecute(    Void result){
      super.onPostExecute(result);
      mActivity.dismissDialog(DIALOG_WIPE_PROGRESS);
      mActivity.startActivity(getLoginIntent(mActivity));
      mActivity.finish();
    }
    @Override protected void onCancelled(){
      super.onCancelled();
      mActivity.dismissDialog(DIALOG_WIPE_PROGRESS);
    }
  }
;
  wipeTask.execute();
}
 

Example 57

From project Ohmage_Phone, under directory /src/org/ohmage/activity/.

Source file: ProfileActivity.java

  15 
vote

/** 
 * 1) Clears the user's data, 2) redirects the user to the login page, and 3) clears the backstack + makes it a new task, so they can't get back into the app
 */
private void clearAndGotoLogin(){
  AsyncTask<Void,Void,Void> wipeTask=new AsyncTask<Void,Void,Void>(){
    @Override protected void onPreExecute(){
      super.onPreExecute();
      showDialog(DIALOG_WIPE_PROGRESS);
    }
    @Override protected Void doInBackground(    Void... params){
      ((OhmageApplication)getApplication()).resetAll();
      return null;
    }
    @Override protected void onPostExecute(    Void result){
      super.onPostExecute(result);
      dismissDialog(DIALOG_WIPE_PROGRESS);
      Intent intent=new Intent(mContext,LoginActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      startActivity(intent);
      finish();
    }
    @Override protected void onCancelled(){
      super.onCancelled();
      dismissDialog(DIALOG_WIPE_PROGRESS);
    }
  }
;
  wipeTask.execute();
}
 

Example 58

From project pandoroid, under directory /src/com/aregner/android/pandoid/.

Source file: PandoraRadioService.java

  15 
vote

@SuppressWarnings("unchecked") public ArrayList<Station> getStations(){
  ArrayList<Station> stations;
  stations=pandora.getStations();
  (new AsyncTask<ArrayList<Station>,Void,Void>(){
    @Override protected Void doInBackground(    ArrayList<Station>... params){
      db=new PandoraDB(getBaseContext());
      db.syncStations(params[0]);
      db.close();
      return null;
    }
  }
).execute(stations);
  return stations;
}
 

Example 59

From project platform_frameworks_ex, under directory /chips/src/com/android/ex/chips/.

Source file: BaseRecipientAdapter.java

  15 
vote

private void fetchPhotoAsync(final RecipientEntry entry,final Uri photoThumbnailUri){
  final AsyncTask<Void,Void,Void> photoLoadTask=new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... params){
      final Cursor photoCursor=mContentResolver.query(photoThumbnailUri,PhotoQuery.PROJECTION,null,null,null);
      if (photoCursor != null) {
        try {
          if (photoCursor.moveToFirst()) {
            final byte[] photoBytes=photoCursor.getBlob(PhotoQuery.PHOTO);
            entry.setPhotoBytes(photoBytes);
            mHandler.post(new Runnable(){
              @Override public void run(){
                mPhotoCacheMap.put(photoThumbnailUri,photoBytes);
                notifyDataSetChanged();
              }
            }
);
          }
        }
  finally {
          photoCursor.close();
        }
      }
      return null;
    }
  }
;
  photoLoadTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
 

Example 60

From project platform_packages_apps_browser, under directory /src/com/android/browser/.

Source file: Bookmarks.java

  15 
vote

/** 
 * Update the bookmark's favicon. This is a convenience method for updating a bookmark favicon for the originalUrl and url of the passed in WebView.
 * @param cr The ContentResolver to use.
 * @param originalUrl The original url before any redirects.
 * @param url The current url.
 * @param favicon The favicon bitmap to write to the db.
 */
static void updateFavicon(final ContentResolver cr,final String originalUrl,final String url,final Bitmap favicon){
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... unused){
      final ByteArrayOutputStream os=new ByteArrayOutputStream();
      favicon.compress(Bitmap.CompressFormat.PNG,100,os);
      ContentValues values=new ContentValues();
      values.put(Images.FAVICON,os.toByteArray());
      updateImages(cr,originalUrl,values);
      updateImages(cr,url,values);
      return null;
    }
    private void updateImages(    final ContentResolver cr,    final String url,    ContentValues values){
      String iurl=removeQuery(url);
      if (!TextUtils.isEmpty(iurl)) {
        values.put(Images.URL,iurl);
        cr.update(BrowserContract.Images.CONTENT_URI,values,null,null);
      }
    }
  }
.execute();
}
 

Example 61

From project platform_packages_apps_contacts, under directory /src/com/android/contacts/.

Source file: CallDetailActivity.java

  15 
vote

private void markVoicemailAsRead(final Uri voicemailUri){
  mAsyncTaskExecutor.submit(Tasks.MARK_VOICEMAIL_READ,new AsyncTask<Void,Void,Void>(){
    @Override public Void doInBackground(    Void... params){
      ContentValues values=new ContentValues();
      values.put(Voicemails.IS_READ,true);
      getContentResolver().update(voicemailUri,values,Voicemails.IS_READ + " = 0",null);
      return null;
    }
  }
);
}
 

Example 62

From project platform_packages_apps_launcher, under directory /src/com/android/launcher/.

Source file: LiveFolder.java

  15 
vote

void bind(FolderInfo info){
  super.bind(info);
  if (mLoadingTask != null && mLoadingTask.getStatus() == AsyncTask.Status.RUNNING) {
    mLoadingTask.cancel(true);
  }
  mLoadingTask=new FolderLoadingTask(this).execute((LiveFolderInfo)info);
}
 

Example 63

From project platform_packages_apps_mms, under directory /src/com/android/mms/data/.

Source file: Conversation.java

  15 
vote

/** 
 * Marks all messages in this conversation as read and updates relevant notifications.  This method returns immediately; work is dispatched to a background thread. This function should always be called from the UI thread.
 */
public void markAsRead(){
  if (mMarkAsReadWaiting) {
    return;
  }
  if (mMarkAsReadBlocked) {
    mMarkAsReadWaiting=true;
    return;
  }
  final Uri threadUri=getUri();
  new AsyncTask<Void,Void,Void>(){
    protected Void doInBackground(    Void... none){
      if (Log.isLoggable(LogTag.APP,Log.VERBOSE)) {
        LogTag.debug("markAsRead");
      }
      if (threadUri != null) {
        buildReadContentValues();
        boolean needUpdate=true;
        Cursor c=mContext.getContentResolver().query(threadUri,UNREAD_PROJECTION,UNREAD_SELECTION,null,null);
        if (c != null) {
          try {
            needUpdate=c.getCount() > 0;
          }
  finally {
            c.close();
          }
        }
        if (needUpdate) {
          LogTag.debug("markAsRead: update read/seen for thread uri: " + threadUri);
          mContext.getContentResolver().update(threadUri,sReadContentValues,UNREAD_SELECTION,null);
        }
        setHasUnreadMessages(false);
      }
      MessagingNotification.blockingUpdateAllNotifications(mContext);
      return null;
    }
  }
.execute();
}
 

Example 64

From project platform_packages_apps_settings, under directory /src/com/android/settings/.

Source file: DataUsageSummary.java

  15 
vote

@Override public void onResume(){
  super.onResume();
  final Intent intent=getActivity().getIntent();
  mIntentTab=computeTabFromIntent(intent);
  updateTabs();
  new AsyncTask<Void,Void,Void>(){
    @Override protected Void doInBackground(    Void... params){
      try {
        Thread.sleep(2 * DateUtils.SECOND_IN_MILLIS);
        mStatsService.forceUpdate();
      }
 catch (      InterruptedException e) {
      }
catch (      RemoteException e) {
      }
      return null;
    }
    @Override protected void onPostExecute(    Void result){
      if (isAdded()) {
        updateBody();
      }
    }
  }
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 

Example 65

From project platform_packages_providers_contactsprovider, under directory /src/com/android/providers/contacts/.

Source file: ContactsProvider2.java

  15 
vote

/** 
 * Opens a file descriptor for a photo to be written.  When the caller completes writing to the file (closing the output stream), the image will be parsed out and processed. If processing succeeds, the given raw contact ID's primary photo record will be populated with the inserted image (if no primary photo record exists, the data ID can be left as 0, and a new data record will be inserted).
 * @param rawContactId Raw contact ID this photo entry should be associated with.
 * @param dataId Data ID for a photo mimetype that will be updated with the insertedimage.  May be set to 0, in which case the inserted image will trigger creation of a new primary photo image data row for the raw contact.
 * @param uri The URI being used to access this file.
 * @param mode Read/write mode string.
 * @return An asset file descriptor the caller can use to write an image file for theraw contact.
 */
private AssetFileDescriptor openDisplayPhotoForWrite(long rawContactId,long dataId,Uri uri,String mode){
  try {
    ParcelFileDescriptor[] pipeFds=ParcelFileDescriptor.createPipe();
    PipeMonitor pipeMonitor=new PipeMonitor(rawContactId,dataId,pipeFds[0]);
    pipeMonitor.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,(Object[])null);
    return new AssetFileDescriptor(pipeFds[1],0,AssetFileDescriptor.UNKNOWN_LENGTH);
  }
 catch (  IOException ioe) {
    Log.e(TAG,"Could not create temp image file in mode " + mode);
    return null;
  }
}
 

Example 66

From project play-android, under directory /app/src/main/java/com/github/play/app/.

Source file: ViewAlbumActivity.java

  15 
vote

@Override protected void refreshSongs(){
  showLoading(true);
  new AsyncTask<Song,Void,SongResult>(){
    @Override protected SongResult doInBackground(    Song... params){
      try {
        return new SongResult(service.get().getSongs(song.artist,song.album));
      }
 catch (      IOException e) {
        return new SongResult(e);
      }
    }
    @Override protected void onPostExecute(    SongResult result){
      displaySongs(result);
    }
  }
.execute(song);
}
 

Example 67

From project playn, under directory /android/src/playn/android/.

Source file: AndroidPlatform.java

  15 
vote

@Override public void invokeAsync(final Runnable action){
  new AsyncTask<Void,Void,Void>(){
    public Void doInBackground(    Void... params){
      try {
        action.run();
      }
 catch (      Exception e) {
        log.warn("Async task failure [task=" + action + "]",e);
      }
      return null;
    }
  }
.execute();
}
 

Example 68

From project RA_Launcher, under directory /src/com/android/ra/launcher/.

Source file: LiveFolder.java

  15 
vote

@Override void bind(FolderInfo info){
  super.bind(info);
  if (mLoadingTask != null && mLoadingTask.getStatus() == AsyncTask.Status.RUNNING) {
    mLoadingTask.cancel(true);
  }
  mLoadingTask=new FolderLoadingTask(this).execute((LiveFolderInfo)info);
}
 

Example 69

From project rbb, under directory /src/com/btmura/android/reddit/app/.

Source file: AccountPreferenceFragment.java

  15 
vote

private void handleRemoveAccount(){
  AccountManager manager=AccountManager.get(getActivity());
  String accountType=AccountAuthenticator.getAccountType(getActivity());
  Account account=new Account(accountName,accountType);
  final AccountManagerFuture<Boolean> result=manager.removeAccount(account,null,null);
  new AsyncTask<Void,Void,Boolean>(){
    @Override protected Boolean doInBackground(    Void... params){
      try {
        return result.getResult();
      }
 catch (      OperationCanceledException e) {
        Log.e(TAG,"handleRemoveAccount",e);
      }
catch (      AuthenticatorException e) {
        Log.e(TAG,"handleRemoveAccount",e);
      }
catch (      IOException e) {
        Log.e(TAG,"handleRemoveAccount",e);
      }
      return false;
    }
    @Override protected void onPostExecute(    Boolean result){
      if (result) {
        PreferenceActivity prefActivity=(PreferenceActivity)getActivity();
        prefActivity.finishPreferencePanel(AccountPreferenceFragment.this,Activity.RESULT_OK,new Intent());
      }
 else {
        Toast.makeText(getActivity(),R.string.error,Toast.LENGTH_SHORT).show();
      }
    }
  }
.execute();
}