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.android.deskclock.alarms.AlarmStateManager.java

/**
 * Used in pre-L devices, where "next alarm" is stored in system settings.
 *//* w w w.  j a v a 2  s  .  c  o m*/
private static void updateNextAlarmInSystemSettings(Context context, AlarmInstance nextAlarm) {
    // Send broadcast message so pre-L AppWidgets will recognize an update
    String timeString = "";
    boolean showStatusIcon = false;
    if (nextAlarm != null) {
        timeString = AlarmUtils.getFormattedTime(context, nextAlarm.getAlarmTime());
        showStatusIcon = true;
    }

    // Set and notify next alarm text to system
    LogUtils.i("Displaying next alarm time: \'" + timeString + '\'');
    // Write directly to NEXT_ALARM_FORMATTED in all pre-L versions
    Settings.System.putString(context.getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, timeString);
    Intent alarmChanged = new Intent(SYSTEM_ALARM_CHANGE_ACTION);
    alarmChanged.putExtra("alarmSet", showStatusIcon);
    context.sendBroadcast(alarmChanged);
}

From source file:com.geekandroid.sdk.sample.JPushReceiver.java

private void processCustomMessage(Context context, Bundle bundle) {
    //       if (MainActivity.isForeground) {
    String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
    String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
    Intent msgIntent = new Intent(MESSAGE_RECEIVED_ACTION);
    msgIntent.putExtra(KEY_MESSAGE, message);
    if (!isEmpty(extras)) {
        try {/*from   w w w.  ja  va 2s. c o m*/
            JSONObject extraJson = new JSONObject(extras);
            if (null != extraJson && extraJson.length() > 0) {
                msgIntent.putExtra(KEY_EXTRAS, extras);
            }
        } catch (JSONException e) {

        }

    }
    context.sendBroadcast(msgIntent);
    //      }
}

From source file:com.stasbar.knowyourself.alarms.AlarmStateManager.java

/**
 * Used in pre-L devices, where "next alarm" is stored in system settings.
 *//* ww w .j a v a2s.  c o  m*/
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.KITKAT)
private static void updateNextAlarmInSystemSettings(Context context, AlarmInstance nextAlarm) {
    // Send broadcast message so pre-L AppWidgets will recognize an update
    String timeString = "";
    boolean showStatusIcon = false;
    if (nextAlarm != null) {
        timeString = AlarmUtils.getFormattedTime(context, nextAlarm.getAlarmTime());
        showStatusIcon = true;
    }

    // Set and notify next alarm text to system
    LogUtils.i("Displaying next alarm time: \'" + timeString + '\'');
    // Write directly to NEXT_ALARM_FORMATTED in all pre-L versions
    Settings.System.putString(context.getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, timeString);
    Intent alarmChanged = new Intent(ACTION_ALARM_CHANGED);
    alarmChanged.putExtra("alarmSet", showStatusIcon);
    context.sendBroadcast(alarmChanged);
}

From source file:cz.maresmar.sfm.service.plugin.PluginUtils.java

/**
 * Starts plugin according to API level//from   ww  w. j a  v  a 2s. c  o  m
 *
 * @param context Some valid context
 * @param intent  Intent of plugin to be started
 * @see JobIntentService#enqueueWork(Context, ComponentName, int, Intent)
 */
public static void startPlugin(@NonNull Context context, @NonNull Intent intent) {
    // Test if the plugin exists
    PackageManager manager = context.getPackageManager();
    if (manager.queryIntentServices(intent, 0).size() != 1) {
        Timber.e("Plugin %s not found", intent.getComponent());
        throw new IllegalArgumentException("Plugin not found " + intent.getComponent());
    }

    // Finds jobId for selected plugin
    String pluginName = ProviderContract.buildString(intent.getComponent());
    int jobId;
    if (!mPluginsIds.containsKey(pluginName)) {
        jobId = mPluginsIds.size();
        mPluginsIds.put(pluginName, jobId);
    } else {
        jobId = mPluginsIds.get(pluginName);
    }

    // Starts plugin according to API level
    if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
            || (context.getPackageName().equals(intent.getComponent().getPackageName()))) {
        JobIntentService.enqueueWork(context, intent.getComponent(), jobId, intent);
    } else {
        // On Android >= O with external plugin use BroadcastContract.BROADCAST_PLAN_RUN to
        // start plugin, because planning of external APK's service is not allowed

        Intent plan = new Intent();
        // Explicitly select a package to communicate with
        plan.setPackage(intent.getComponent().getPackageName());
        plan.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);

        plan.setAction(ActionContract.BROADCAST_PLAN_RUN);
        plan.putExtra(ActionContract.EXTRA_JOB_ID, jobId);
        plan.putExtra(ActionContract.EXTRA_INTENT_TO_DO, intent);
        context.sendBroadcast(plan);
    }
}

From source file:com.onesignal.OneSignal.java

private static void fireIntentFromNotificationOpen(Context inContext, JSONArray data) {
    PackageManager packageManager = inContext.getPackageManager();

    boolean isCustom = false;

    Intent intent = new Intent().setAction("com.onesignal.NotificationOpened.RECEIVE")
            .setPackage(inContext.getPackageName());

    List<ResolveInfo> resolveInfo = packageManager.queryBroadcastReceivers(intent,
            PackageManager.GET_INTENT_FILTERS);
    if (resolveInfo.size() > 0) {
        intent.putExtra("onesignal_data", data.toString());
        inContext.sendBroadcast(intent);
        isCustom = true;//from  w  w w.  j a v  a2s.co m
    }

    // Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag.
    resolveInfo = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    if (resolveInfo.size() > 0) {
        if (!isCustom)
            intent.putExtra("onesignal_data", data.toString());
        isCustom = true;
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
        inContext.startActivity(intent);
    }

    if (!isCustom) {
        try {
            ApplicationInfo ai = inContext.getPackageManager().getApplicationInfo(inContext.getPackageName(),
                    PackageManager.GET_META_DATA);
            Bundle bundle = ai.metaData;
            String defaultStr = bundle.getString("com.onesignal.NotificationOpened.DEFAULT");
            isCustom = "DISABLE".equals(defaultStr);
        } catch (Throwable t) {
            Log(LOG_LEVEL.ERROR, "", t);
        }
    }

    if (!isCustom) {
        Intent launchIntent = inContext.getPackageManager()
                .getLaunchIntentForPackage(inContext.getPackageName());

        if (launchIntent != null) {
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            inContext.startActivity(launchIntent);
        }
    }
}

From source file:cm.aptoide.ptdev.preferences.ManagerPreferences.java

public void createLauncherShortcut(Context context, int drawable) {

    //removeLauncherShortcut(context);

    Intent shortcutIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
    Log.d("Aptoide-Shortcut", "Creating Intent");
    final Intent intent = new Intent();
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, Aptoide.getConfiguration().getMarketName());

    Parcelable iconResource;/*from   www. ja  v a 2  s. c o m*/

    iconResource = Intent.ShortcutIconResource.fromContext(context, drawable);

    intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
    intent.putExtra("duplicate", false);
    intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");

    context.sendBroadcast(intent);

}

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

/**
 * Asks the captcha solver app to solve the captcha.
 *///from www .  java  2  s  .  co m
private String solveCaptchaWithSolver(final Context context, final Bitmap captcha) {
    Log.d(TAG, "requesting captcha answer from Captcha Solver");
    CabbageConnector.receivedCaptchaAnswer = null;

    // send request to captcha solver app
    final Intent intent = CaptcherSolverClient.createRequestIntent(captcha);
    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:com.browsertophone.AppEngineClient.java

private String getAuthToken(Context context, Account account) {
    String authToken = null;/*from www . j  av a  2s . c o  m*/
    AccountManager accountManager = AccountManager.get(context);
    try {
        AccountManagerFuture<Bundle> future = accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, false, null,
                null);
        Bundle bundle = future.getResult();
        authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
        // User will be asked for "App Engine" permission.
        if (authToken == null) {
            // No auth token - will need to ask permission from user.
            Intent intent = new Intent(SetupActivity.AUTH_PERMISSION_ACTION);
            intent.putExtra("AccountManagerBundle", bundle);
            context.sendBroadcast(intent);
        }
    } catch (OperationCanceledException e) {
        Log.w(TAG, e.getMessage());
    } catch (AuthenticatorException e) {
        Log.w(TAG, e.getMessage());
    } catch (IOException e) {
        Log.w(TAG, e.getMessage());
    }
    return authToken;
}

From source file:com.notifry.android.C2DMReceiver.java

public void onRegistered(Context context, String registration) throws IOException {
    Log.i("Notifry", "registered and got key: " + registration);

    // Dispatch this to the updater service.
    Intent intentData = new Intent(getBaseContext(), UpdaterService.class);
    intentData.putExtra("type", "registration");
    intentData.putExtra("registration", registration);
    startService(intentData);//w  ww  .  j av  a2 s  .  c om

    // Clear any errors we had.
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    Editor editor = settings.edit();
    editor.putString("dm_register_error", "");
    editor.commit();

    // Update the home screen.
    Intent updateUIIntent = new Intent(Notifry.UPDATE_INTENT);
    context.sendBroadcast(updateUIIntent);
}

From source file:net.sourceforge.subsonic.androidapp.util.Util.java

/**
 * <p>Broadcasts the given song info as the new song being played.</p>
 *//*from ww w.j  av  a 2  s  .  c om*/
public static void broadcastNewTrackInfo(Context context, MusicDirectory.Entry song) {
    Intent intent = new Intent(EVENT_META_CHANGED);
    Intent avrcpIntent = new Intent("com.android.music.metachanged");

    if (song != null) {
        intent.putExtra("title", song.getTitle());
        intent.putExtra("artist", song.getArtist());
        intent.putExtra("album", song.getAlbum());

        //avrcp intent
        avrcpIntent.putExtra("id", song.getId());
        avrcpIntent.putExtra("track", song.getTitle());
        avrcpIntent.putExtra("artist", song.getArtist());
        avrcpIntent.putExtra("album", song.getAlbum());

        File albumArtFile = FileUtil.getAlbumArtFile(context, song);
        intent.putExtra("coverart", albumArtFile.getAbsolutePath());
    } else {
        intent.putExtra("title", "");
        intent.putExtra("artist", "");
        intent.putExtra("album", "");
        intent.putExtra("coverart", "");

        avrcpIntent.putExtra("id", "");
        avrcpIntent.putExtra("track", "");
        avrcpIntent.putExtra("artist", "");
        avrcpIntent.putExtra("album", "");
    }

    context.sendBroadcast(intent);
    context.sendBroadcast(avrcpIntent);
}