android.os.AsyncTask Java Examples

The following examples show how to use android.os.AsyncTask. 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 File: WebappAuthenticator.java    From 365browser with 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 #2
Source File: LoginButton.java    From FacebookImageShareIntent with 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 #3
Source File: GithubRemoteDataSource.java    From gito-github-client with 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 #4
Source File: DeviceGroupsHelper.java    From gcm with 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 #5
Source File: RemoveWhiteListReceiver.java    From ForceDoze with 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 #6
Source File: PDFView.java    From AndroidPDF with 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 #7
Source File: FileExpandableAdapter.java    From ShareBox with 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 #8
Source File: SceneMainView.java    From flowless with 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 #9
Source File: ContactsManager.java    From react-native-contacts with 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 #10
Source File: ExifUtil.java    From Camera-Roll-Android-App with 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 File: UniformSampler2dPageFragment.java    From ShaderEditor with 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 #12
Source File: ContactsManager.java    From react-native-contacts with 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 #13
Source File: GCMUtils.java    From buddycloud-android with 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 #14
Source File: OpenPgpApi.java    From FairEmail with 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 #15
Source File: PublishFormFragment.java    From lbry-android with 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 #16
Source File: WifiResultHandler.java    From barcodescanner-lib-aar with 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 #17
Source File: Chest.java    From Iron with Apache License 2.0 5 votes vote down vote up
public void removeAllAsync() {
    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            deleteAll();
            return null;
        }
    };
    if (Build.VERSION.SDK_INT > 10) {
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {
        task.execute();
    }
}
 
Example #18
Source File: StorageClientFragment.java    From storage-samples with Apache License 2.0 5 votes vote down vote up
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mDialog = super.onCreateDialog(savedInstanceState);
    // To optimize for the "lightbox" style layout.  Since we're not actually displaying a
    // title, remove the bar along the top of the fragment where a dialog title would
    // normally go.
    mDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    final ImageView imageView = new ImageView(getActivity());
    mDialog.setContentView(imageView);

    // BEGIN_INCLUDE (show_image)
    // Loading the image is going to require some sort of I/O, which must occur off the UI
    // thread.  Changing the ImageView to display the image must occur ON the UI thread.
    // The easiest way to divide up this labor is with an AsyncTask.  The doInBackground
    // method will run in a separate thread, but onPostExecute will run in the main
    // UI thread.
    AsyncTask<Uri, Void, Bitmap> imageLoadAsyncTask = new AsyncTask<Uri, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(Uri... uris) {
            dumpImageMetaData(uris[0]);
            return getBitmapFromUri(uris[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            imageView.setImageBitmap(bitmap);
        }
    };
    imageLoadAsyncTask.execute(mUri);
    // END_INCLUDE (show_image)

    return mDialog;
}
 
Example #19
Source File: AutoFocusManager.java    From Gizwits-SmartBuld_Android with MIT License 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 #20
Source File: Utils.java    From tup.dota2recipe with Apache License 2.0 5 votes vote down vote up
/**
 * execute AsyncTask
 * 
 * @param task
 */
@SuppressLint("NewApi")
public static <Params, Progress, Result> void executeAsyncTask(
        AsyncTask<Params, Progress, Result> loaderTask, Params... params) {
    if (loaderTask == null) {
        return;
    }

    if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
        loaderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    } else {
        loaderTask.execute(params);
    }
}
 
Example #21
Source File: ExecutorProviderHelper.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static Executor getInstance() {
  if (Looper.myLooper() == Looper.getMainLooper() && Looper.getMainLooper() != null) {
    return TaskExecutors.MAIN_THREAD;
  }

  return AsyncTask.THREAD_POOL_EXECUTOR;
}
 
Example #22
Source File: BindBean96AsyncTask.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Method to start operations.
 *
 * @param executor used executor
 * @param data input
 */
public void executeOnExecutor(Executor executor, @SuppressWarnings("unchecked") I... params) {
  asyncTask=new AsyncTask<I, U, R>() {
    @Override
    public void onPreExecute() {
      BindBean96AsyncTask.this.onPreExecute();
    }

    @Override
    public R doInBackground(@SuppressWarnings("unchecked") I... params) {
      BindBean96DataSource dataSource=BindBean96DataSource.getInstance();
      R result=onExecute(dataSource);
      return result;
    }

    @Override
    public void onProgressUpdate(@SuppressWarnings("unchecked") U... values) {
      BindBean96AsyncTask.this.onProgressUpdate(values);
    }

    @Override
    public void onPostExecute(R result) {
      BindBean96AsyncTask.this.onFinish(result);
    }
  };
  asyncTask.executeOnExecutor(executor, params);
}
 
Example #23
Source File: AndroidUtils.java    From Android-Next with Apache License 2.0 5 votes vote down vote up
/**
 * Execute an {@link AsyncTask} on a thread pool.
 *
 * @param task Task to add.
 * @param args Optional arguments to pass to {@link AsyncTask#execute(Object[])}.
 * @param <T>  Task argument type.
 */
@SuppressWarnings("unchecked")
@TargetApi(VERSION_CODES.HONEYCOMB)
public static <T> void execute(AsyncTask<T, ?, ?> task, T... args) {
    if (Build.VERSION.SDK_INT < VERSION_CODES.HONEYCOMB) {
        task.execute(args);
    } else {
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, args);
    }
}
 
Example #24
Source File: DeleteObjectsSample.java    From huaweicloud-sdk-java-obs with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    sb = new StringBuffer();
    
    ObsConfiguration config = new ObsConfiguration();
    config.setSocketTimeout(30000);
    config.setConnectionTimeout(10000);
    config.setEndPoint(endPoint);
    
    /*
    * Constructs a obs client instance with your account for accessing OBS
    */
    obsClient = new ObsClient(ak, sk, config);
    final TextView tv = (TextView)findViewById(R.id.tv);
    tv.setText("Click to start test");
    
    tv.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            tv.setClickable(false);
            AsyncTask<Void, Void, String> task = new DeleteObjectsTask();
            task.execute();
        }
    });
}
 
Example #25
Source File: ImageLoader.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
private void runArtworkTasks(boolean complete) {
    if (complete) {
        currentArtworkTasksCount--;
    }
    while (currentArtworkTasksCount < 4 && !artworkTasks.isEmpty()) {
        try {
            ArtworkLoadTask task = artworkTasks.poll();
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
            currentArtworkTasksCount++;
        } catch (Throwable ignore) {
            runArtworkTasks(false);
        }
    }
}
 
Example #26
Source File: WebService.java    From webi with Apache License 2.0 5 votes vote down vote up
private void startBackground() {
    @SuppressLint("StaticFieldLeak")
    AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {

            configs();

            return null;
        }
    };
    asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
 
Example #27
Source File: GPDialogs.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Execute a message dialog with clickable links in an {@link AsyncTask}.
 *
 * @param context      the {@link Context} to use.
 * @param msg          the message to show.
 * @param iconResource the icon resource to use or -1 fro default.
 * @param okRunnable   optional {@link Runnable} to trigger after ok was pressed.
 */
public static void messageDialogWithLink(final Context context, final String msg, final int iconResource, final Runnable okRunnable) {

    final SpannableString s = new SpannableString(msg);
    Linkify.addLinks(s, Linkify.ALL);

    new AsyncTask<String, Void, String>() {
        protected String doInBackground(String... params) {
            return ""; //$NON-NLS-1$
        }

        protected void onPostExecute(String response) {
            try {
                int icon = iconResource;
                if (icon == -1) {
                    icon = android.R.drawable.ic_dialog_info;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder //
                        .setMessage(s)
                        .setIcon(icon).setCancelable(true)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (okRunnable != null) {
                                    new Thread(okRunnable).start();
                                }
                            }
                        });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();

                ((TextView) alertDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
            } catch (Exception e) {
                GPLog.error("UTILITIES", "Error in messageDialog#inPostExecute -- " + msg, e); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
    }.execute((String) null);
}
 
Example #28
Source File: AdBlocker.java    From Slide with GNU General Public License v3.0 5 votes vote down vote up
public static void init(final Context context) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                loadFromAssets(context);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }.execute();
}
 
Example #29
Source File: Home.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_export_database) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                return DatabaseUtil.saveSql(getBaseContext());
            }

            @Override
            protected void onPostExecute(String filename) {
                super.onPostExecute(filename);

                final Context ctx = getApplicationContext();

                Toast.makeText(ctx, "Export stored at " + filename, Toast.LENGTH_SHORT).show();

                final NotificationCompat.Builder n = new NotificationCompat.Builder(ctx);
                n.setContentTitle("Export complete");
                n.setContentText("Ready to be sent.");
                n.setAutoCancel(true);
                n.setSmallIcon(R.drawable.ic_action_communication_invert_colors_on);
                ShareNotification.viewOrShare("application/octet-stream", Uri.fromFile(new File(filename)), n, ctx);

                final NotificationManager manager = (NotificationManager) ctx.getSystemService(Service.NOTIFICATION_SERVICE);
                manager.notify(Notifications.exportCompleteNotificationId, n.build());
            }
        }.execute();

        return true;
    }
    return super.onOptionsItemSelected(item);
}
 
Example #30
Source File: RecentMediaStorage.java    From AndroidTvDemo with Apache License 2.0 5 votes vote down vote up
public void saveUrlAsync(String url)
{
    new AsyncTask<String, Void, Void>()
    {
        @Override
        protected Void doInBackground(String... params)
        {
            saveUrl(params[0]);
            return null;
        }
    }.execute(url);
}