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.nit.vicky.servicelayer.NoteService.java

/**
 * Considering the field is new, if it has media handle it
 * //from w w w  .j  a v  a 2 s  .  c om
 * @param field
 */
private static void importMediaToDirectory(IField field, Context context) {
    String tmpMediaPath = null;
    switch (field.getType()) {
    case AUDIO:
        tmpMediaPath = field.getAudioPath();
        break;

    case IMAGE:
        tmpMediaPath = field.getImagePath();
        break;

    case TEXT:
    default:
        break;
    }
    if (tmpMediaPath != null) {
        try {
            File inFile = new File(tmpMediaPath);
            if (inFile.exists()) {
                Collection col = AnkiDroidApp.getCol();
                String mediaDir = col.getMedia().getDir() + "/";

                File mediaDirFile = new File(mediaDir);

                File parent = inFile.getParentFile();

                // If already there.
                if (mediaDirFile.getAbsolutePath().contentEquals(parent.getAbsolutePath())) {
                    return;
                }

                //File outFile = new File(mediaDir + inFile.getName().replaceAll(" ", "_"));

                //if (outFile.exists()) {

                File outFile = null;

                if (field.getType() == EFieldType.IMAGE) {
                    outFile = File.createTempFile("imggallery", ".jpg", DiskUtil.getStoringDirectory());
                } else if (field.getType() == EFieldType.AUDIO) {
                    outFile = File.createTempFile("soundgallery", ".mp3", DiskUtil.getStoringDirectory());
                }

                //}

                if (field.hasTemporaryMedia()) {
                    // Move
                    inFile.renameTo(outFile);
                } else {
                    // Copy
                    InputStream in = new FileInputStream(tmpMediaPath);
                    OutputStream out = new FileOutputStream(outFile.getAbsolutePath());

                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    in.close();
                    out.close();
                }

                switch (field.getType()) {
                case AUDIO:
                    field.setAudioPath(outFile.getAbsolutePath());
                    break;

                case IMAGE:
                    field.setImagePath(outFile.getAbsolutePath());
                    break;
                default:
                    break;
                }

                Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                scanIntent.setData(Uri.fromFile(inFile));
                context.sendBroadcast(scanIntent);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.mk4droid.IMC_Services.DatabaseHandler.java

/**
 *            Categories : Insert categories or update categories table
 *   //from   www .  ja  v a 2s  . c  o  m
 * @return number of downloaded bytes 
 */
public int addUpdCateg(Context ctx) {

    int bdown = 0;

    String response = Download_Data.Download_Categories();

    if (response != null)
        bdown += response.length();

    try {
        JSONArray jArrCategs = new JSONArray(response);
        int NCateg = jArrCategs.length();

        if (!db.isOpen())
            db = this.getWritableDatabase();

        //--------- Create Helpers for Local db -----------------
        final InsertHelper iHelpC = new InsertHelper(db, TABLE_Categories);

        int c1 = iHelpC.getColumnIndex(KEY_CatID);
        int c2 = iHelpC.getColumnIndex(KEY_CatName);
        int c3 = iHelpC.getColumnIndex(KEY_CatIcon);
        int c4 = iHelpC.getColumnIndex(KEY_CatLevel);
        int c5 = iHelpC.getColumnIndex(KEY_CatParentID);
        int c6 = iHelpC.getColumnIndex(KEY_CatVisible);

        try {
            db.beginTransaction();
            Log.e("UPD", "Categs");
            for (int i = 0; i < NCateg; i++) {

                float prog = 100 * ((float) (i + 1)) / ((float) NCateg);

                ctx.sendBroadcast(
                        new Intent("android.intent.action.MAIN").putExtra("progressval", (int) (prog * 0.67)));

                JSONArray jArrData = new JSONArray(jArrCategs.get(i).toString());

                int CategID = jArrData.getInt(0);
                String CategName = jArrData.getString(1);
                int CategLevel = jArrData.getInt(2);
                int CategParentId = jArrData.getInt(3);
                String CategParams = jArrData.getString(4);

                JSONObject cpOb = new JSONObject(CategParams);
                String CategIconPath = cpOb.getString("image");

                String fullPath = Constants_API.COM_Protocol + Constants_API.ServerSTR
                        + Constants_API.remoteImages + CategIconPath;

                // Download icon
                byte[] CategIcon = Download_Data.Down_Image(fullPath);

                //------- Resize icon based on the device needs and store in db. --------------------
                Bitmap CategIconBM = BitmapFactory.decodeByteArray(CategIcon, 0, CategIcon.length);
                CategIconBM = Bitmap.createScaledBitmap(CategIconBM,
                        (int) ((float) Fragment_Map.metrics.densityDpi / 4.5),
                        (int) ((float) Fragment_Map.metrics.densityDpi / 4), true);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                CategIconBM.compress(Bitmap.CompressFormat.PNG, 100, stream);
                CategIcon = stream.toByteArray();
                //---------------------------------------------------------

                bdown += CategIcon.length;

                // Local db
                Cursor cursorC = db.rawQuery("SELECT " + KEY_CatID + "," + KEY_CatVisible + " FROM "
                        + TABLE_Categories + " WHERE " + KEY_CatID + "=" + Integer.toString(CategID), null);

                if (cursorC.moveToFirst()) { // Update 
                    iHelpC.prepareForReplace();
                    iHelpC.bind(c6, cursorC.getInt(1) == 1);
                } else {
                    iHelpC.prepareForInsert();
                    iHelpC.bind(c6, 1); // Insert
                }

                iHelpC.bind(c1, CategID);
                iHelpC.bind(c2, CategName);
                iHelpC.bind(c3, CategIcon);
                iHelpC.bind(c4, CategLevel);
                iHelpC.bind(c5, CategParentId);
                cursorC.close();

                iHelpC.execute();
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        } // TRY OF TRANSACTION 
    } catch (JSONException e1) {
        e1.printStackTrace();
        Log.e(Constants_API.TAG, TAG_Class + ": Categories update failed");
    } // TRY OF JSONARRAY

    return bdown;
}

From source file:github.daneren2005.dsub.util.Util.java

/**
 * <p>Broadcasts the given song info as the new song being played.</p>
 *//*  www  .  jav a 2 s.  c o  m*/
public static void broadcastNewTrackInfo(Context context, MusicDirectory.Entry song) {
    DownloadService downloadService = (DownloadServiceImpl) context;
    Intent intent = new Intent(EVENT_META_CHANGED);
    Intent avrcpIntent = new Intent(AVRCP_METADATA_CHANGED);

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

        File albumArtFile = FileUtil.getAlbumArtFile(context, song);
        intent.putExtra("coverart", albumArtFile.getAbsolutePath());

        avrcpIntent.putExtra("playing", true);
        avrcpIntent.putExtra("track", song.getTitle());
        avrcpIntent.putExtra("artist", song.getArtist());
        avrcpIntent.putExtra("album", song.getAlbum());
        avrcpIntent.putExtra("ListSize", (long) downloadService.getSongs().size());
        avrcpIntent.putExtra("id", (long) downloadService.getCurrentPlayingIndex() + 1);
        avrcpIntent.putExtra("duration", (long) downloadService.getPlayerDuration());
        avrcpIntent.putExtra("position", (long) downloadService.getPlayerPosition());
        avrcpIntent.putExtra("coverart", albumArtFile.getAbsolutePath());
    } else {
        intent.putExtra("title", "");
        intent.putExtra("artist", "");
        intent.putExtra("album", "");
        intent.putExtra("coverart", "");

        avrcpIntent.putExtra("playing", false);
        avrcpIntent.putExtra("track", "");
        avrcpIntent.putExtra("artist", "");
        avrcpIntent.putExtra("album", "");
        avrcpIntent.putExtra("ListSize", (long) 0);
        avrcpIntent.putExtra("id", (long) 0);
        avrcpIntent.putExtra("duration", (long) 0);
        avrcpIntent.putExtra("position", (long) 0);
        avrcpIntent.putExtra("coverart", "");
    }

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

From source file:com.parse.CN1ParsePushBroadcastReceiver.java

@Override
protected void onPushReceive(Context context, Intent intent) {
    /*//from   ww  w. j a va2s.  c  om
     Adapted from ParsePushBroadcastReceiver.onPushReceived(). Main changes:
     1. Implemented callbacks to ParsePush with the push payload based on
    app state
     */

    JSONObject pushData = null;
    try {
        pushData = new JSONObject(intent.getStringExtra(ParsePushBroadcastReceiver.KEY_PUSH_DATA));
    } catch (JSONException e) {
        writeErrorLog("Unexpected JSONException when parsing received push data:\n" + e);
    }
    writeDebugLog("Push received: " + (pushData == null ? "<no payload>" : pushData.toString()));

    boolean handled = false;
    if (pushData != null && CN1AndroidApplication.isAppRunning()) {
        if (CN1AndroidApplication.isAppInForeground()) {
            writeDebugLog("App in foreground; will allow app to directly handle push message, if desired");
            handled = ParsePush.handlePushReceivedForeground(pushData.toString());
        } else if (CN1AndroidApplication.isAppInBackground()) {
            writeDebugLog("App in background; will allow app to directly handle push message, if desired");
            handled = ParsePush.handlePushReceivedBackground(pushData.toString());
        }
    }

    if (!handled) {
        // 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) {
            writeDebugLog("Firing broadcast for action " + action);
            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) {
            writeDebugLog("Scheduling notification for push message since it was not handled by app");
            ParseNotificationManager.getInstance().showNotification(context, notification);
        } else {
            // If, for any reason, creating the notification fails (typically because
            // the push is a 'hidden' push with no alert/title fields),
            // store it for later processing.
            if (pushData != null) {
                writeDebugLog("Requesting ParsePush to handle unprocessed (hidden?) push message");
                ParsePush.handleUnprocessedPushReceived(pushData.toString());
            }
        }
    } else {
        writeDebugLog("Push already handled by app so not scheduling any notification");
    }
}

From source file:org.restcomm.app.utillib.Reporters.ReportManager.java

public int startDriveTest(Context context, int minutes, boolean coverage, int speed, int connectivity, int sms,
        int video, int audio, int web, int vq, int youtube, int ping) {
    JSONObject settings = new JSONObject();
    try {/*from   w  w w .j a  v a  2  s .  c  o  m*/
        // Trigger certain events using the Library
        settings.put("dur", minutes / 5);
        settings.put("cov", coverage ? 1 : 0);
        settings.put("spd", speed);
        settings.put("ct", connectivity);
        settings.put("sms", sms);
        settings.put("vid", video);
        settings.put("audio", audio);
        settings.put("web", web);
        settings.put("vq", vq);
        settings.put("youtube", youtube);
        settings.put("ping", ping);

        JSONObject jobj = new JSONObject();
        jobj.put("mmctype", "rt");
        jobj.put("settings", settings);

        String command = "[" + jobj.toString() + "]";
        Intent mmcintent = new Intent(CommonIntentActionsOld.COMMAND);
        mmcintent.putExtra(CommonIntentActionsOld.COMMAND_EXTRA, command);
        context.sendBroadcast(mmcintent);

        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putString(PreferenceKeys.Miscellaneous.DRIVE_TEST_CMD, jobj.toString()).commit();

    } catch (Exception e) {
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "startDriveTest", "exception", e);
    }

    return 0;
}

From source file:com.liato.bankdroid.appwidget.AutoRefreshService.java

public static void showNotification(final Bank bank, final Account account, final BigDecimal diff,
        Context context) {

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (!prefs.getBoolean("notify_on_change", true)) {
        return;/*from  ww w. j ava2  s  .  c o m*/
    }

    String text = String.format("%s: %s%s", account.getName(),
            ((diff.compareTo(new BigDecimal(0)) == 1) ? "+" : ""),
            Helpers.formatBalance(diff, account.getCurrency()));
    if (!prefs.getBoolean("notify_delta_only", false)) {
        text = String.format("%s (%s)", text,
                Helpers.formatBalance(account.getBalance(), account.getCurrency()));
    }

    final NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(NOTIFICATION_SERVICE);
    final NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
            .setSmallIcon(bank.getImageResource()).setContentTitle(bank.getDisplayName()).setContentText(text);

    // Remove notification from statusbar when clicked
    notification.setAutoCancel(true);

    // http://www.freesound.org/samplesViewSingle.php?id=75235
    // http://www.freesound.org/samplesViewSingle.php?id=91924
    if (prefs.getString("notification_sound", null) != null) {
        notification.setSound(Uri.parse(prefs.getString("notification_sound", null)));
    }
    if (prefs.getBoolean("notify_with_vibration", true)) {
        final long[] vib = { 0, 90, 130, 80, 350, 190, 20, 380 };
        notification.setVibrate(vib);
    }

    if (prefs.getBoolean("notify_with_led", true)) {
        notification.setLights(prefs.getInt("notify_with_led_color",
                context.getResources().getColor(R.color.default_led_color)), 700, 200);
    }

    final PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, MainActivity.class), 0);
    notification.setContentIntent(contentIntent);

    String numNotifications = prefs.getString("num_notifications", "total");
    int notificationId = (int) (numNotifications.equals("total") ? 0
            : numNotifications.equals("bank") ? bank.getDbId()
                    : numNotifications.equals("account") ? account.getId().hashCode()
                            : SystemClock.elapsedRealtime());
    notificationManager.notify(notificationId, notification.build());

    // Broadcast to Remote Notifier if enabled
    // http://code.google.com/p/android-notifier/
    if (prefs.getBoolean("notify_remotenotifier", false)) {
        final Intent i = new Intent(BROADCAST_REMOTE_NOTIFIER);
        i.putExtra("title", String.format("%s (%s)", bank.getName(), bank.getDisplayName()));
        i.putExtra("description", text);
        context.sendBroadcast(i);
    }

    // Broadcast to OpenWatch if enabled
    // http://forum.xda-developers.com/showthread.php?t=554551
    if (prefs.getBoolean("notify_openwatch", false)) {
        Intent i;
        if (prefs.getBoolean("notify_openwatch_vibrate", false)) {
            i = new Intent(BROADCAST_OPENWATCH_VIBRATE);
        } else {
            i = new Intent(BROADCAST_OPENWATCH_TEXT);
        }
        i.putExtra("line1", String.format("%s (%s)", bank.getName(), bank.getDisplayName()));
        i.putExtra("line2", text);
        context.sendBroadcast(i);
    }

    // Broadcast to LiveView if enabled
    // http://www.sonyericsson.com/cws/products/accessories/overview/liveviewmicrodisplay
    if (prefs.getBoolean("notify_liveview", false)) {
        final Intent i = new Intent(context, LiveViewService.class);
        i.putExtra(LiveViewService.INTENT_EXTRA_ANNOUNCE, true);
        i.putExtra(LiveViewService.INTENT_EXTRA_TITLE,
                String.format("%s (%s)", bank.getName(), bank.getDisplayName()));
        i.putExtra(LiveViewService.INTENT_EXTRA_TEXT, text);
        context.startService(i);
    }

}

From source file:com.openerp.services.UserGroupsSyncService.java

/**
 * Perform sync./*from   ww  w  .  j av  a2  s. c  om*/
 * 
 * @param context
 *            the context
 * @param account
 *            the account
 * @param extras
 *            the extras
 * @param authority
 *            the authority
 * @param provider
 *            the provider
 * @param syncResult
 *            the sync result
 */
public void performSync(Context context, Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {
    // TODO Auto-generated method stub
    try {
        UserGroupsDb usergroups = new UserGroupsDb(context);
        Intent intent = new Intent();
        intent.setAction(SyncFinishReceiver.SYNC_FINISH);
        if (OpenERPServerConnection.isNetworkAvailable(context)) {
            Log.i(TAG + "::performSync()", "Sync with Server Started");
            OEHelper oe = usergroups.getOEInstance();
            if (oe.syncWithServer(usergroups, null, false, false)) {
                MailFollowerDb group_follower = new MailFollowerDb(context);
                OEHelper oe_1 = group_follower.getOEInstance();
                JSONObject domain = new JSONObject();
                int partner_id = Integer.parseInt(OpenERPAccountManager.currentUser(context).getPartner_id());
                domain.accumulate("domain", new JSONArray("[[\"partner_id\", \"=\", " + partner_id
                        + "],[\"res_model\",\"=\", \"" + usergroups.getModelName() + "\"]]"));

                if (oe_1.syncWithServer(group_follower, domain, false, false)) {
                    Log.i(TAG, "UserGroups Sync Finished");
                    MailFollowerDb follower = new MailFollowerDb(context);
                    List<HashMap<String, Object>> user_groups = follower.executeSQL(follower.getModelName(),
                            new String[] { "res_id" },
                            new String[] { "partner_id = ?", "AND", "res_model = ?" },
                            new String[] { partner_id + "", "mail.group" });
                    JSONArray group_ids = new JSONArray();
                    if (user_groups.size() > 0) {
                        for (HashMap<String, Object> row : user_groups) {
                            group_ids.put(Integer.parseInt(row.get("res_id").toString()));
                        }
                    }
                    context.sendBroadcast(intent);
                    Bundle bundle = new Bundle();
                    bundle.putString("group_ids", group_ids.toString());
                    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
                    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
                    ContentResolver.requestSync(account, MessageProvider.AUTHORITY, bundle);
                }

            }

        } else {
            Log.e("OpenERPServerConnection", "Unable to Connect with server");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:dev.ukanth.ufirewall.Api.java

/**
 * Defines if the firewall is enabled and broadcasts the new status
 * @param ctx mandatory context/*  w  w w . j a  v a  2 s. c o m*/
 * @param enabled enabled flag
 */
public static void setEnabled(Context ctx, boolean enabled, boolean showErrors) {
    if (ctx == null)
        return;
    final SharedPreferences prefs = ctx.getSharedPreferences(PREF_FIREWALL_STATUS, Context.MODE_PRIVATE);
    if (prefs.getBoolean(PREF_ENABLED, false) == enabled) {
        return;
    }
    rulesUpToDate = false;

    final Editor edit = prefs.edit();
    edit.putBoolean(PREF_ENABLED, enabled);
    if (!edit.commit()) {
        if (showErrors)
            alert(ctx, ctx.getString(R.string.error_write_pref));
        return;
    }

    if (G.activeNotification()) {
        Api.showNotification(Api.isEnabled(ctx), ctx);
    }

    /* notify */
    final Intent message = new Intent(Api.STATUS_CHANGED_MSG);
    message.putExtra(Api.STATUS_EXTRA, enabled);
    ctx.sendBroadcast(message);
}

From source file:pj.rozkladWKD.C2DMReceiver.java

@Override
public void onMessage(Context context, Intent intent) {
    Bundle extras = intent.getExtras();//from  w  w w.  j  a v a2 s  .  c om
    if (!Prefs.get(context).getBoolean(Prefs.PUSH_TURNED_ON, true)) {
        RozkladWKDApplication app = (RozkladWKDApplication) getApplication();
        SharedPreferences.Editor edit = Prefs.get(context).edit();
        edit.putBoolean(Prefs.PUSH_TURNED_ON, false);
        edit.commit();
        app.registerPushes();
    } else {
        if (extras != null) {
            String type = (String) extras.get("type");
            String msg = (String) extras.get("msg");
            String username = (String) extras.get("usr");

            if (RozkladWKD.DEBUG_LOG) {
                Log.d("PUSH", type + ": " + msg);
            }

            String[] categories = Prefs.getStringArray(context, Prefs.PUSH_CATEGORIES,
                    Prefs.DEFAULT_PUSH_CATEGORIES);

            Prefs.getNotificationMessageNextNumber(context, type);
            if (!username.equals(Prefs.get(context).getString(Prefs.USERNAME, "")) && categories != null
                    && type != null) {
                for (String category : categories) {
                    if (type.equals(category)) {
                        Intent notificationIntent = new Intent(this, MessageActivity.class);
                        notificationIntent.putExtra("page", type.equals(MessagesPagerAdapter.MESSAGE_EVENTS) ? 0
                                : (type.equals(MessagesPagerAdapter.MESSAGE_WKD) ? 1 : 2));
                        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

                        showNotification(msg,
                                String.format(getString(R.string.new_message),
                                        getResources().getString(getResources().getIdentifier(type, "string",
                                                context.getPackageName()))),
                                msg, contentIntent, Prefs.getNotificationMessageNextNumber(context));
                        break;
                    }
                }
            }
            context.sendBroadcast(new Intent("com.google.ctp.UPDATE_UI"));

        }
    }
}

From source file:com.negaheno.android.NotificationsController.java

private void setBadge(final Context context, final int count) {
    notificationsQueue.postRunnable(new Runnable() {
        @Override/*from  ww  w . jav  a 2s  .  co m*/
        public void run() {
            try {
                ContentValues cv = new ContentValues();
                cv.put("tag", "com.negaheno.messenger/LaunchActivity");
                cv.put("count", count);
                context.getContentResolver()
                        .insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv);
            } catch (Throwable e) {
                //ignore
            }
            try {
                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);
            }
        }
    });
}