Java Code Examples for android.os.AsyncTask

The following examples show how to use android.os.AsyncTask. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: lbry-android   Author: lbryio   File: PublishFormFragment.java    License: MIT License 6 votes vote down vote up
private void fetchChannels() {
    if (Lbry.ownChannels != null && Lbry.ownChannels.size() > 0) {
        updateChannelList(Lbry.ownChannels);
        return;
    }

    fetchingChannels = true;
    disableChannelSpinner();
    ClaimListTask task = new ClaimListTask(Claim.TYPE_CHANNEL, progressLoadingChannels, new ClaimListResultHandler() {
        @Override
        public void onSuccess(List<Claim> claims) {
            Lbry.ownChannels = new ArrayList<>(claims);
            updateChannelList(Lbry.ownChannels);
            enableChannelSpinner();
            fetchingChannels = false;
        }

        @Override
        public void onError(Exception error) {
            enableChannelSpinner();
            fetchingChannels = false;
        }
    });
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example #2
Source Project: gcm   Author: google   File: DeviceGroupsHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Execute in background the HTTP calls to add and remove members.
 */
public void asyncUpdateGroup(final String senderId, final String apiKey,
                             final String groupName, final String groupKey,
                             Bundle newMembers, Bundle removedMembers) {
    final Bundle members2Add = new Bundle(newMembers);
    final Bundle members2Remove = new Bundle(removedMembers);
    new AsyncTask<Void, Void, Void>(){
        @Override
        protected Void doInBackground(Void... voids) {
            if (members2Add.size() > 0) {
                addMembers(senderId, apiKey, groupName, groupKey, members2Add);
            }
            if (members2Remove.size() > 0) {
                removeMembers(senderId, apiKey, groupName, groupKey, members2Remove);
            }
            return null;
        }
    }.execute();
}
 
Example #3
Source Project: ForceDoze   Author: theblixguy   File: RemoveWhiteListReceiver.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Log.i(TAG, "com.suyashsrijan.forcedoze.REMOVE_WHITELIST broadcast intent received");
    final String packageName = intent.getStringExtra("packageName");
    Log.i(TAG, "Package name received: " + packageName);
    if (packageName != null) {
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                List<String> output = Shell.SH.run("dumpsys deviceidle whitelist -" + packageName);
                if (output != null) {
                    for (String s : output) {
                        Log.i(TAG, s);
                    }
                } else {
                    Log.i(TAG, "Error occurred while executing command (" + "dumpsys deviceidle whitelist -packagename" + ")");
                }
            }
        });
    } else {
        Log.i(TAG, "Package name null or empty");
    }
}
 
Example #4
Source Project: flowless   Author: Zhuinden   File: SceneMainView.java    License: Apache License 2.0 6 votes vote down vote up
private void goToSecondSceneWithDelay() {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Log.d(TAG, "Do In Background");
                Thread.sleep(3000);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Log.d(TAG, "OnPostExecute");
            super.onPostExecute(aVoid);
            Flow.get(SceneMainView.this).set(SceneMainSecondKey.create());
        }
    }.execute();
}
 
Example #5
Source Project: react-native-contacts   Author: morenoh149   File: ContactsManager.java    License: MIT License 6 votes vote down vote up
/**
 * Retrieves contacts matching an email address.
 * Uses raw URI when <code>rawUri</code> is <code>true</code>, makes assets copy otherwise.
 *
 * @param emailAddress email address to match
 * @param callback user provided callback to run at completion
 */
@ReactMethod
public void getContactsByEmailAddress(final String emailAddress, final Callback callback) {
    AsyncTask<Void,Void,Void> myAsyncTask = new AsyncTask<Void,Void,Void>() {
        @Override
        protected Void doInBackground(final Void ... params) {
            Context context = getReactApplicationContext();
            ContentResolver cr = context.getContentResolver();
            ContactsProvider contactsProvider = new ContactsProvider(cr);
            WritableArray contacts = contactsProvider.getContactsByEmailAddress(emailAddress);

            callback.invoke(null, contacts);
            return null;
        }
    };
    myAsyncTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
 
Example #6
Source Project: ShaderEditor   Author: markusfisch   File: UniformSampler2dPageFragment.java    License: MIT License 6 votes vote down vote up
@SuppressLint("StaticFieldLeak")
private void loadTexturesAsync(final Context context) {
	if (context == null) {
		return;
	}

	new AsyncTask<Void, Void, Cursor>() {
		@Override
		protected Cursor doInBackground(Void... nothings) {
			return loadTextures();
		}

		@Override
		protected void onPostExecute(Cursor cursor) {
			if (!isAdded() || cursor == null) {
				return;
			}

			updateAdapter(context, cursor);
		}
	}.execute();
}
 
Example #7
Source Project: 365browser   Author: mogoweb   File: WebappAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates the authentication encryption key in a background thread (if necessary).
 */
private static void triggerMacKeyGeneration() {
    synchronized (sLock) {
        if (sKey != null || sMacKeyGenerator != null) {
            return;
        }

        sMacKeyGenerator = new FutureTask<SecretKey>(new Callable<SecretKey>() {
            // SecureRandomInitializer addresses the bug in SecureRandom that "TrulyRandom"
            // warns about, so this lint warning can safely be suppressed.
            @SuppressLint("TrulyRandom")
            @Override
            public SecretKey call() throws Exception {
                KeyGenerator generator = KeyGenerator.getInstance(MAC_ALGORITHM_NAME);
                SecureRandom random = new SecureRandom();
                SecureRandomInitializer.initialize(random);
                generator.init(MAC_KEY_BYTE_COUNT * 8, random);
                return generator.generateKey();
            }
        });
        AsyncTask.THREAD_POOL_EXECUTOR.execute(sMacKeyGenerator);
    }
}
 
Example #8
Source Project: barcodescanner-lib-aar   Author: EddyVerbruggen   File: WifiResultHandler.java    License: MIT License 6 votes vote down vote up
@Override
public void handleButtonPress(int index) {
  if (index == 0) {
    WifiParsedResult wifiResult = (WifiParsedResult) getResult();
    WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
    if (wifiManager == null) {
      Log.w(TAG, "No WifiManager available from device");
      return;
    }
    final Activity activity = getActivity();
    activity.runOnUiThread(new Runnable() {
      @Override
      public void run() {
        Toast.makeText(activity.getApplicationContext(), R.string.wifi_changing_network, Toast.LENGTH_SHORT).show();
      }
    });
    new WifiConfigManager(wifiManager).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, wifiResult);
    parent.restartPreviewAfterDelay(0L);
  }
}
 
Example #9
Source Project: buddycloud-android   Author: buddycloud   File: GCMUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method unregister from the GCM services and also pusher
 * server in the background mode. 
 * 
 * @param context
 */
public static void unregisterInBackground(final Context context) {
	
	new AsyncTask<Void, Void, String>() {

		@Override
		protected String doInBackground(Void... params) {

			try {
				GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
				gcm.unregister();
				
				// Unregister the GCM info from pusher server.
				String regId = Preferences.getPreference(context, Preferences.CURRENT_GCM_ID);
				GCMIntentService.removeFromPusher(context, regId);
			} catch (IOException e) {
				Logger.error(TAG, "GCM Un-registration failed.", e);
			} 
			
			return null;
		}
	}.execute();
}
 
Example #10
Source Project: Camera-Roll-Android-App   Author: kollerlukas   File: ExifUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void saveChanges(final ExifInterface exifInterface,
                               final List<ExifItem> editedItems, final Callback callback) {
    if (exifInterface == null) {
        return;
    }
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            boolean success = true;
            for (ExifItem item : editedItems) {
                exifInterface.setAttribute(item.getTag(), item.getValue());
            }
            try {
                exifInterface.saveAttributes();
            } catch (IOException e) {
                e.printStackTrace();
                success = false;
            }

            if (callback != null) {
                callback.done(success);
            }
        }
    });
}
 
Example #11
Source Project: react-native-contacts   Author: morenoh149   File: ContactsManager.java    License: MIT License 6 votes vote down vote up
/**
 * Retrieves <code>thumbnailPath</code> for contact, or <code>null</code> if not available.
 *
 * @param contactId contact identifier, <code>recordID</code>
 * @param callback callback
 */
@ReactMethod
public void getPhotoForId(final String contactId, final Callback callback) {
    AsyncTask<Void,Void,Void> myAsyncTask = new AsyncTask<Void,Void,Void>() {
        @Override
        protected Void doInBackground(final Void ... params) {
            Context context = getReactApplicationContext();
            ContentResolver cr = context.getContentResolver();
            ContactsProvider contactsProvider = new ContactsProvider(cr);
            String photoUri = contactsProvider.getPhotoUriFromContactId(contactId);

            callback.invoke(null, photoUri);
            return null;
        }
    };
    myAsyncTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
 
Example #12
Source Project: FairEmail   Author: M66B   File: OpenPgpApi.java    License: GNU General Public License v3.0 6 votes vote down vote up
public <T> CancelableBackgroundOperation executeApiAsync(Intent data, OpenPgpDataSource dataSource,
        OpenPgpDataSink<T> dataSink, final IOpenPgpSinkResultCallback<T> callback) {
    Messenger messenger = new Messenger(new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            callback.onProgress(message.arg1, message.arg2);
            return true;
        }
    }));
    data.putExtra(EXTRA_PROGRESS_MESSENGER, messenger);

    OpenPgpSourceSinkAsyncTask<T> task = new OpenPgpSourceSinkAsyncTask<>(data, dataSource, dataSink, callback);

    // don't serialize async tasks!
    // http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);

    return task;
}
 
Example #13
Source Project: ShareBox   Author: Kerr1Gan   File: FileExpandableAdapter.java    License: Apache License 2.0 6 votes vote down vote up
protected void setGroupViewThumb(FileUtil.MediaFileType type, String thumb, ImageView icon, TextView text, RequestOptions options) {
    if (type == FileUtil.MediaFileType.MOVIE ||
            type == FileUtil.MediaFileType.IMG) {
        if (options == null) {
            Glide.with(mContext).load(thumb).listener(mRequestListener).into(icon);
        } else {
            Glide.with(mContext).load(thumb).listener(mRequestListener).apply(options).into(icon);
        }
    } else if (type == FileUtil.MediaFileType.APP) {
        Bitmap b = sLruCache.get(thumb);
        if (b == null) {
            AppThumbTask task = new AppThumbTask(sLruCache, mContext, icon);
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new File(thumb));
        } else
            icon.setImageBitmap(b);
    } else if (type == FileUtil.MediaFileType.MP3) {
        text.setText(R.string.music);
    } else if (type == FileUtil.MediaFileType.DOC) {
        text.setText(R.string.doc);
    } else if (type == FileUtil.MediaFileType.RAR) {
        text.setText(R.string.rar);
    }
}
 
Example #14
Source Project: AndroidPDF   Author: lidong1665   File: PDFView.java    License: Apache License 2.0 6 votes vote down vote up
private void load(Uri uri, OnLoadCompleteListener onLoadCompleteListener, int[] userPages) {

        if (!recycled) {
            throw new IllegalStateException("Don't call load on a PDF View without recycling it first.");
        }

        // Manage UserPages if not null
        if (userPages != null) {
            this.originalUserPages = userPages;
            this.filteredUserPages = ArrayUtils.deleteDuplicatedPages(originalUserPages);
            this.filteredUserPageIndexes = ArrayUtils.calculateIndexesInDuplicateArray(originalUserPages);
        }

        this.onLoadCompleteListener = onLoadCompleteListener;

        // Start decoding document
        decodingAsyncTask = new DecodingAsyncTask(uri, this);
        decodingAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        renderingAsyncTask = new RenderingAsyncTask(this);
        renderingAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
 
Example #15
Source Project: FacebookImageShareIntent   Author: b099l3   File: LoginButton.java    License: MIT License 6 votes vote down vote up
private void checkNuxSettings() {
    if (nuxMode == ToolTipMode.DISPLAY_ALWAYS) {
        String nuxString = getResources().getString(R.string.com_facebook_tooltip_default);
        displayNux(nuxString);
    } else {
        // kick off an async request
        final String appId = Utility.getMetadataApplicationId(getContext());
        AsyncTask<Void, Void, FetchedAppSettings> task = new AsyncTask<Void, Void, Utility.FetchedAppSettings>() {
            @Override
            protected FetchedAppSettings doInBackground(Void... params) {
                FetchedAppSettings settings = Utility.queryAppSettings(appId, false);
                return settings;
            }

            @Override
            protected void onPostExecute(FetchedAppSettings result) {
                showNuxPerSettings(result);
            }
        };
        task.execute((Void[])null);
    }

}
 
Example #16
Source Project: gito-github-client   Author: DmitryMalkovich   File: GithubRemoteDataSource.java    License: Apache License 2.0 6 votes vote down vote up
public void getStargazers(final Repository repository, final GetStargazersCallback callback) {
    new AsyncTask<Void, Void, List<Star>>() {
        @Override
        protected List<Star> doInBackground(Void... params) {
            return getStargazersSync(repository);
        }

        @Override
        protected void onPostExecute(List<Star> starList) {
            if (starList != null) {
                callback.onStargazersLoaded(starList);
            } else {
                callback.onDataNotAvailable();
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example #17
Source Project: QuranAndroid   Author: fekracomputers   File: DownloadManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Action after download finished of not
 *
 * @param result flag download success or not
 */
@Override
protected void onPostExecute(Boolean result) {

    //notify download complete
    if (context != null)
        Toast.makeText(context, result == true ?
                        context.getString(R.string.download_complete) :
                        context.getString(R.string.download_failed)
                , Toast.LENGTH_LONG).show();

    //pass the download statue to notification
    if (notificationDownloaderFlag) {
        notificationManager.cancel(0);
        if (result) {
            showCompleteNotification();
            AppPreference.DownloadStatues(AppConstants.Preferences.DOWNLOAD_SUCCESS);
        } else {
            showFailedNotification();
            AppPreference.DownloadStatues(AppConstants.Preferences.DOWNLOAD_FAILED);
        }
    }

    //run extraction service if zip file or stop service
    if (fileExtension.toLowerCase().equals("zip") && result) {
        new UnZipping(context).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, filePath, fileName);
    } else {
        //send broadcast of success or failed
        LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(AppConstants.Download.INTENT)
                .putExtra(AppConstants.Download.DOWNLOAD, result == true ?
                        AppConstants.Download.SUCCESS :
                        AppConstants.Download.FAILED));
        if (context instanceof Service)
            ((Service) context).stopService(new Intent(context, DownloadService.class));
    }

}
 
Example #18
Source Project: ghwatch   Author: Daskiworks   File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
protected void markNotificationAsReadOnShow(int position, Notification notification) {
  try {
    new MarkNotificationAsReadTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, notification.getId());
    ActivityTracker.sendEvent(MainActivity.this, ActivityTracker.CAT_UI, "notification_mark_read_on_show", "", 0L);
    notificationsListAdapter.removeNotificationByPosition(position);
    notifyDataSetChanged();
  } catch (RejectedExecutionException e) {
    //nothing to do
  }
}
 
Example #19
Source Project: mobile-manager-tool   Author: hubcarl   File: ImageProvider.java    License: MIT License 5 votes vote down vote up
private void asyncLoad(String tag, ImageView imageView, AsyncTask<String, Integer, Bitmap> task) {
    Set<ImageView> pendingImages = pendingImagesMap.get(tag);
    if (pendingImages == null) {
        pendingImages = Collections.newSetFromMap(new WeakHashMap<ImageView, Boolean>()); // create weak set
        pendingImagesMap.put(tag, pendingImages);
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
    pendingImages.add(imageView);
    imageView.setTag(tag);
    imageView.setImageDrawable(null);
}
 
Example #20
Source Project: zxingfragmentlib   Author: mitoyarzun   File: SupplementalInfoRetriever.java    License: Apache License 2.0 5 votes vote down vote up
public static void maybeInvokeRetrieval(TextView textView,
                                        ParsedResult result,
                                        HistoryManager historyManager,
                                        Context context) {
  if (result instanceof URIParsedResult) {
    SupplementalInfoRetriever uriRetriever = 
        new URIResultInfoRetriever(textView, (URIParsedResult) result, historyManager, context);
    uriRetriever.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    SupplementalInfoRetriever titleRetriever = 
        new TitleRetriever(textView, (URIParsedResult) result, historyManager);
    titleRetriever.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
  } else if (result instanceof ProductParsedResult) {
    ProductParsedResult productParsedResult = (ProductParsedResult) result;
    String productID = productParsedResult.getProductID();
    SupplementalInfoRetriever productRetriever =
        new ProductResultInfoRetriever(textView, productID, historyManager, context);
    productRetriever.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
  } else if (result instanceof ISBNParsedResult) {
    String isbn = ((ISBNParsedResult) result).getISBN();
    SupplementalInfoRetriever productInfoRetriever = 
        new ProductResultInfoRetriever(textView, isbn, historyManager, context);
    productInfoRetriever.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    SupplementalInfoRetriever bookInfoRetriever = 
        new BookResultInfoRetriever(textView, isbn, historyManager, context);
    bookInfoRetriever.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
  }
}
 
Example #21
Source Project: CameraV   Author: guardianproject   File: OverviewFormFragment.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void initData()
{
	IMedia media = ((EditorActivityListener) a).media();

	String[] dateAndTime = TimeUtility.millisecondsToDatestampAndTimestamp(((EditorActivityListener) a).media().dcimEntry.timeCaptured);
	
	historyHeaderSubTitle.setText(getString(R.string.editor_image_taken, dateAndTime[0] + " " + dateAndTime[1]));

	AsyncTask<Void, Void, List<INotification>> taskLoadNotifications = new AsyncTask<Void, Void, List<INotification>>()
	{
		@Override
		protected List<INotification> doInBackground(Void... params) {
			return InformaCam.getInstance().notificationsManifest.sortBy(Models.INotificationManifest.Sort.DATE_DESC);
		}

		@Override
		protected void onPostExecute(List<INotification> result) {
			super.onPostExecute(result);
			lvHistory.setAdapter(new MediaHistoryListAdapter(a, ((EditorActivityListener) a).media()._id, result));	
			
			if (lvHistory.getAdapter().getCount() == 0)
			{
				historyHeader.setOnClickListener(null);
			//	showHistoryIndicator.setVisibility(View.GONE);
			}
			else
			{
				historyHeader.setOnClickListener(OverviewFormFragment.this);
			//	showHistoryIndicator.setVisibility(View.VISIBLE);
			}
		}		
	};
	taskLoadNotifications.execute((Void)null);
}
 
Example #22
Source Project: coolreader   Author: dotcool   File: DisplayTeaserListActivity.java    License: MIT License 5 votes vote down vote up
@SuppressLint("NewApi")
private void executeDownloadTask(ArrayList<PageModel> novels) {
	downloadTask = new DownloadNovelDetailsTask(this);
	String key = DisplayTeaserListActivity.TAG + ":" + novels.get(0).getPage();
	if (novels == null || novels.size() == 0) {
		Log.w(TAG, getResources().getString(R.string.error_empty_download_array));
		return;
	}
	if (novels.size() > 1) {
		key = DisplayTeaserListActivity.TAG + ":All_Teasers";
	}
	boolean isAdded = LNReaderApplication.getInstance().addTask(key, task);
	if (isAdded) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
			downloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, novels.toArray(new PageModel[novels.size()]));
		else
			downloadTask.execute(novels.toArray(new PageModel[novels.size()]));
	} else {
		Log.i(TAG, "Continue download task: " + key);
		DownloadNovelDetailsTask tempTask = (DownloadNovelDetailsTask) LNReaderApplication.getInstance().getTask(key);
		if (tempTask != null) {
			downloadTask = tempTask;
			downloadTask.owner = this;
		}
		toggleProgressBar(true);
	}
}
 
Example #23
Source Project: candybar-library   Author: danimahardhika   File: FAQsFragment.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    setFastScrollColor(mFastScroll);
    mFastScroll.attachRecyclerView(mRecyclerView);

    mAsyncTask = new FAQsLoader().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example #24
Source Project: SimplifyReader   Author: chentao0707   File: AutoFocusManager.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void autoFocusAgainLater() {
    if (!stopped && outstandingTask == null) {
        AutoFocusTask newTask = new AutoFocusTask();
        try {
            if (Build.VERSION.SDK_INT >= 11) {
                newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            } else {
                newTask.execute();
            }
            outstandingTask = newTask;
        } catch (RejectedExecutionException ree) {
            Log.w(TAG, "Could not request auto focus", ree);
        }
    }
}
 
Example #25
Source Project: ProjectX   Author: AlexMofer   File: AutoFocusManager.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void cancelOutstandingTask() {
    if (outstandingTask != null) {
        if (outstandingTask.getStatus() != AsyncTask.Status.FINISHED) {
            outstandingTask.cancel(true);
        }
        outstandingTask = null;
    }
}
 
Example #26
Source Project: wallpaperboard   Author: danimahardhika   File: WallpapersFragment.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),
            getActivity().getResources().getInteger(R.integer.wallpapers_column_count)));
    mRecyclerView.setHasFixedSize(false);

    if (WallpaperBoardApplication.getConfig().getWallpapersGrid() ==
            WallpaperBoardConfiguration.GridStyle.FLAT) {
        int padding = getActivity().getResources().getDimensionPixelSize(R.dimen.card_margin);
        mRecyclerView.setPadding(padding, padding, 0, 0);
    }
    resetViewBottomPadding(mRecyclerView, true);

    mSwipe.setColorSchemeColors(ColorHelper.getAttributeColor(
            getActivity(), R.attr.colorAccent));
    mSwipe.setOnRefreshListener(() -> {
        if (mAsyncTask != null) {
            mSwipe.setRefreshing(false);
            return;
        }

        WallpapersLoaderTask.with(getActivity()).start();
        mAsyncTask = new WallpapersTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
    });

    getWallpapers();
}
 
Example #27
Source Project: zxing   Author: yuzhiqiang1993   File: InactivityTimer.java    License: MIT License 5 votes vote down vote up
private synchronized void cancel() {
	AsyncTask<?, ?, ?> task = inactivityTask;
	if (task != null) {
		task.cancel(true);
		inactivityTask = null;
	}
}
 
Example #28
Source Project: mage-android   Author: ngageoint   File: ChangeEventActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void finishEvent(final Event event) {
	// Send chosen event to the server
	List<String> userRecentEventInfo = new ArrayList<>();
	userRecentEventInfo.add(event.getRemoteId());
	new RecentEventTask(new AccountDelegate() {
		@Override
		public void finishAccount(AccountStatus accountStatus) {
			// no-op, don't care if server didn't get event selection
		}
	}, getApplicationContext()).execute(userRecentEventInfo.toArray(new String[userRecentEventInfo.size()]));

	try {
		UserHelper userHelper = UserHelper.getInstance(getApplicationContext());
		User user = userHelper.readCurrentUser();
		userHelper.setCurrentEvent(user, event);
	} catch (UserException e) {
		Log.e(LOG_NAME, "Could not set current event.", e);
	}

	// disable pushing locations
	if (!UserHelper.getInstance(getApplicationContext()).isCurrentUserPartOfEvent(event)) {
		SharedPreferences.Editor sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
		sp.putBoolean(getString(R.string.reportLocationKey), false).apply();
	}


	AsyncTask.execute(new Runnable() {
		@Override
		public void run() {
			new ObservationServerFetch(getApplicationContext()).fetch(false);
		}
	});

	setResult(RESULT_OK);
	finish();
}
 
Example #29
Source Project: mollyim-android   Author: mollyim   File: MarkReadReceiver.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SuppressLint("StaticFieldLeak")
@Override
public void onReceive(final Context context, Intent intent) {
  if (!CLEAR_ACTION.equals(intent.getAction()))
    return;

  final long[] threadIds = intent.getLongArrayExtra(THREAD_IDS_EXTRA);

  if (threadIds != null) {
    NotificationManagerCompat.from(context).cancel(intent.getIntExtra(NOTIFICATION_ID_EXTRA, -1));

    new AsyncTask<Void, Void, Void>() {
      @Override
      protected Void doInBackground(Void... params) {
        List<MarkedMessageInfo> messageIdsCollection = new LinkedList<>();

        for (long threadId : threadIds) {
          Log.i(TAG, "Marking as read: " + threadId);
          List<MarkedMessageInfo> messageIds = DatabaseFactory.getThreadDatabase(context).setRead(threadId, true);
          messageIdsCollection.addAll(messageIds);
        }

        process(context, messageIdsCollection);

        ApplicationDependencies.getMessageNotifier().updateNotification(context);

        return null;
      }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
  }
}
 
Example #30
Source Project: PasscodeView   Author: kevalpatel2106   File: PinView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Handle the newly added key digit. Append the digit to {@link #mPinTyped}.
 * If the new digit is {@link KeyNamesBuilder#BACKSPACE_TITLE}, remove the last digit of the {@link #mPinTyped}.
 *
 * @param newDigit newly pressed digit
 */
private void onKeyPressed(@Nullable String newDigit) {
    if (newDigit == null) return;

    //Check for the state
    if (mAuthenticationListener == null) {
        throw new IllegalStateException("Set AuthenticationListener to receive callbacks.");
    }

    if (newDigit.equals(KeyNamesBuilder.BACKSPACE_TITLE)) { //Back space key is pressed.
        if (mPinTyped.size() > 0) mPinTyped.remove(mPinTyped.size() - 1);   //Remove last digit.
    } else {

        //Add new digit
        mPinTyped.add(mKeyNamesBuilder.getValueOfKey(newDigit));
    }

    invalidate();

    if (isDynamicPinEnabled() || mPinTyped.size() == mBoxIndicator.getPinLength()) {
        if (mPinAuthenticatorTask != null && mPinAuthenticatorTask.getStatus() == AsyncTask.Status.RUNNING)
            mPinAuthenticatorTask.cancel(true);

        mPinAuthenticatorTask = new PinAuthenticatorTask(mAuthenticator);
        //noinspection unchecked
        mPinAuthenticatorTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mPinTyped);
    } else {
        giveTactileFeedbackForKeyPress();
    }

}