Example usage for android.content Context sendBroadcast

List of usage examples for android.content Context sendBroadcast

Introduction

In this page you can find the example usage for android.content Context sendBroadcast.

Prototype

public abstract void sendBroadcast(@RequiresPermission Intent intent);

Source Link

Document

Broadcast the given intent to all interested BroadcastReceivers.

Usage

From source file:com.parse.ParsePushBroadcastReceiver.java

/**
 * Called when the push notification is received. By default, a broadcast intent will be sent if
 * an "action" is present in the data and a notification will be show if "alert" and "title" are
 * present in the data.//from   w  w  w  .j  a  v  a 2 s.  com
 *
 * @param context
 *      The {@code Context} in which the receiver is running.
 * @param intent
 *      An {@code Intent} containing the channel and data of the current push notification.
 */
protected void onPushReceive(Context context, Intent intent) {
    String pushDataStr = intent.getStringExtra(KEY_PUSH_DATA);
    if (pushDataStr == null) {
        PLog.e(TAG, "Can not get push data from intent.");
        return;
    }
    PLog.v(TAG, "Received push data: " + pushDataStr);

    JSONObject pushData = null;
    try {
        pushData = new JSONObject(pushDataStr);
    } catch (JSONException e) {
        PLog.e(TAG, "Unexpected JSONException when receiving push data: ", e);
    }

    // If the push data includes an action string, that broadcast intent is fired.
    String action = null;
    if (pushData != null) {
        action = pushData.optString("action", null);
    }
    if (action != null) {
        Bundle extras = intent.getExtras();
        Intent broadcastIntent = new Intent();
        broadcastIntent.putExtras(extras);
        broadcastIntent.setAction(action);
        broadcastIntent.setPackage(context.getPackageName());
        context.sendBroadcast(broadcastIntent);
    }

    Notification notification = getNotification(context, intent);

    if (notification != null) {
        ParseNotificationManager.getInstance().showNotification(context, notification);
    }
}

From source file:org.adblockplus.android.configurators.ManualProxyConfigurator.java

private synchronized void noTrafficReceived() {
    this.isRegistered = false;
    this.abortNoTrafficCheck();

    this.uiHandler.post(new Runnable() {
        @Override/*from  ww  w. j av  a 2 s .  co m*/
        public void run() {
            final Context context = ManualProxyConfigurator.this.context;
            // Show warning notification
            final Intent intent = new Intent(context, ConfigurationActivity.class)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .putExtra("port", ManualProxyConfigurator.this.proxyProperties.getPort());

            final PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.ic_stat_warning).setWhen(System.currentTimeMillis())
                    .setAutoCancel(true).setContentIntent(contentIntent)
                    .setContentTitle(context.getText(R.string.app_name))
                    .setContentText(context.getText(R.string.notif_notraffic));

            final NotificationManager notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(NOTRAFFIC_NOTIFICATION_ID, builder.getNotification());

            context.sendBroadcast(new Intent(ProxyService.PROXY_STATE_CHANGED_ACTION));
        }
    });
}

From source file:com.p2p.misc.DeviceUtility.java

public void toggleGPS(boolean enable, Context mContext) {
    try {/*from w  ww  .  ja  v a 2s .c  o  m*/
        String provider = Settings.Secure.getString(mContext.getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        //    Intent I = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        //       mContext.startActivity(I);
        if (!provider.contains("gps")) { //if gps is disabled
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            mContext.sendBroadcast(poke);
            System.out.println("GPS is turn ON");
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.psiphon3.psiphonlibrary.UpgradeChecker.java

/**
 * Checks whether an upgrade check should be performed. False will be returned if there's already
 * an upgrade file downloaded./*w w w. j  a  va2 s  . c om*/
 * May be called from any process or thread.
 * Side-effect: If an existing upgrade file is detected, the upgrade notification will be displayed.
 * Side-effect: Creates the UpgradeChecker alarm.
 * @param context the context
 * @return true if upgrade check is needed.
 */
public static boolean upgradeCheckNeeded(Context context) {
    Context appContext = context.getApplicationContext();

    // The main process will call this when it tries to connect, so we will use this opportunity
    // to make sure our alarm is created.
    createAlarm(appContext);

    // Don't re-download the upgrade package when a verified upgrade file is
    // awaiting application by the user. A previous upgrade download will have
    // completed and have been extracted to this verified upgrade file.
    // Without this check, tunnel-core won't know that the upgrade is already
    // downloaded, as the file name differs from UpgradeDownloadFilename, and
    // so the entire upgrade will be re-downloaded on each tunnel connect until
    // the user actually applies the upgrade.
    // As a result of this check, a user that delays applying an upgrade until
    // after a subsequent upgrade is released will first apply a stale upgrade
    // and then download the next upgrade.
    // Note: depends on getAvailableCompleteUpgradeFile deleting VerifiedUpgradeFile
    // after upgrade is complete. Otherwise, no further upgrades would download.
    // TODO: implement version tracking for the verified upgrade file so that
    // we can proceed with downloading a newer upgrade when an outdated upgrade exists
    // on disk.

    if (!allowedToSelfUpgrade(context)) {
        log(context, R.string.upgrade_checker_no_upgrading, MyLog.Sensitivity.NOT_SENSITIVE, Log.WARN);
        return false;
    }

    if (UpgradeManager.UpgradeInstaller.upgradeFileAvailable(appContext)) {
        log(context, R.string.upgrade_checker_upgrade_file_exists, MyLog.Sensitivity.NOT_SENSITIVE, Log.WARN);
        // We know there's an upgrade file available, so send an intent about it.
        Intent intent = new Intent(appContext, UpgradeChecker.class);
        intent.setAction(UPGRADE_FILE_AVAILABLE_INTENT_ACTION);
        appContext.sendBroadcast(intent);
        return false;
    }

    // Verify if 'Download upgrades on WiFi only' user preference is on
    // but current network is not WiFi
    final AppPreferences multiProcessPreferences = new AppPreferences(appContext);
    if (multiProcessPreferences.getBoolean(context.getString(R.string.downloadWifiOnlyPreference),
            PsiphonConstants.DOWNLOAD_WIFI_ONLY_PREFERENCE_DEFAULT) && !Utils.isOnWiFi(appContext)) {
        log(context, R.string.upgrade_checker_upgrade_wifi_only, MyLog.Sensitivity.NOT_SENSITIVE, Log.WARN);
        return false;
    }

    log(appContext, R.string.upgrade_checker_check_needed, MyLog.Sensitivity.NOT_SENSITIVE, Log.WARN);

    return true;
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

public static Bitmap entityToBitmap(Context context, HttpEntity entity, final String contentId,
        boolean withProgressBar, Long contentSize) {
    try {/*  ww w.  j  a  va  2  s  . c o m*/
        File file = new File(getDir(), contentId);
        file.createNewFile();
        InputStream is = entity.getContent();

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1)
         * and write on the fly in the file.
         */
        final FileOutputStream fos = new FileOutputStream(file);
        final int BUFFER_SIZE = 23 * 1024;
        BufferedInputStream bis = new BufferedInputStream(is, BUFFER_SIZE);
        byte[] baf = new byte[BUFFER_SIZE];
        int actual = 0;
        long total = 0;
        int totalpercent = 0;
        int auxtotal = 0;

        while (actual != -1) {
            fos.write(baf, 0, actual);
            actual = bis.read(baf, 0, BUFFER_SIZE);

            if (withProgressBar) {
                try {
                    total = total + actual;
                    auxtotal = (int) (((total * 100) / contentSize)) / 10;
                    if ((totalpercent != auxtotal) && (totalpercent != 10)) {
                        totalpercent = auxtotal;
                        Intent intent = new Intent();
                        intent.setAction(ConstantKeys.BROADCAST_DIALOG_PROGRESSBAR);
                        intent.putExtra(ConstantKeys.TOTAL, totalpercent * 10);
                        intent.putExtra(ConstantKeys.LOCALID,
                                contentId.replace(ConstantKeys.EXTENSION_3GP, ConstantKeys.STRING_DEFAULT)
                                        .replace(ConstantKeys.EXTENSION_JPG, ConstantKeys.STRING_DEFAULT));
                        context.sendBroadcast(intent);
                    }
                } catch (Exception e) {
                    log.error("Error tryng to send broadcast to progressbar", e);
                }
            }
        }

        fos.close();

        if (contentId.contains(ConstantKeys.EXTENSION_JPG)) {
            return decodeSampledBitmapFromPath(file.getAbsolutePath(), 200, 200);
        } else {
            return ThumbnailUtils.createVideoThumbnail(file.getAbsolutePath(),
                    MediaStore.Images.Thumbnails.MINI_KIND);
        }

    } catch (Exception e) {
        new File(getDir(), contentId).delete();
        return null;
    }
}

From source file:com.android.mms.transaction.MessagingNotification.java

private static void notifyUserIfFullScreen(Context context, String from) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTasks = am.getRunningTasks(1);

    if (runningTasks.size() > 0) {
        String topActivity = runningTasks.get(0).topActivity.getClassName();
        Log.d(TAG, "checkIsFullScreenMode: the top activity is: " + topActivity);
        if ((topActivity != null) && (topActivity.equals("com.android.browser.BrowserActivity"))) {
            Intent intent = new Intent("com.android.mms.transaction.MESSAGE_RECEIVED");
            intent.putExtra("from", from);
            context.sendBroadcast(intent);
        }//from w  w w .java  2 s. c om
    }
}

From source file:com.mikebl71.android.websms.connector.cabbage.CabbageConnector.java

/**
 * Asks user to solve the captcha.//  w w w  . j  a va 2  s  .c  o m
 */
private String solveCaptchaWithUser(final Context context, final Bitmap captcha, final boolean wasSolverUsed) {
    Log.d(TAG, "requesting captcha answer from user");
    CabbageConnector.receivedCaptchaAnswer = null;

    // send request to WebSMS
    final Intent intent = new Intent(Connector.ACTION_CAPTCHA_REQUEST);
    getSpec(context).setToIntent(intent);
    intent.putExtra(Connector.EXTRA_CAPTCHA_DRAWABLE, captcha);
    if (CaptcherSolverClient.shouldRemind(context)) {
        intent.putExtra(Connector.EXTRA_CAPTCHA_MESSAGE,
                context.getString(R.string.websms_captcha_text_with_tip));
    } else if (wasSolverUsed) {
        intent.putExtra(Connector.EXTRA_CAPTCHA_MESSAGE,
                context.getString(R.string.websms_captcha_text_auto_failed));
    } else {
        intent.putExtra(Connector.EXTRA_CAPTCHA_MESSAGE, context.getString(R.string.websms_captcha_text));
    }
    context.sendBroadcast(intent);

    // wait for answer
    try {
        synchronized (CAPTCHA_SYNC) {
            CAPTCHA_SYNC.wait(CAPTCHA_ANSWER_TIMEOUT);
        }
    } catch (InterruptedException e) {
    }

    return CabbageConnector.receivedCaptchaAnswer;
}

From source file:me.cpwc.nibblegram.android.NotificationsController.java

private void setBadge(Context context, int count) {
    try {/*  w ww  . j av  a  2 s  .  c o  m*/
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", launcherClassName);
        context.sendBroadcast(intent);
    } catch (Throwable e) {
        FileLog.e("tmessages", e);
    }
}

From source file:kr.ac.kpu.wheeling.blackbox.Camera2VideoFragment.java

public void startMediaScanning(Context context, String fileName) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        final Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://" + getVideoStorageDir("wheeling") + "/" + fileName));
        //final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        //final Uri contentUri = Uri.fromFile(file);
        //scanIntent.setData(contentUri);
        context.sendBroadcast(intent);
        Log.d("BROADCAST", "Broadcast Complete!");
    } else {//from  w  ww .  j  a  va  2 s . c  o  m
        final Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory()));
        context.sendBroadcast(intent);
        Log.d("BROADCAST", "Broadcast Complete!(Low ver)");
    }
}