Example usage for android.content BroadcastReceiver BroadcastReceiver

List of usage examples for android.content BroadcastReceiver BroadcastReceiver

Introduction

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

Prototype

public BroadcastReceiver() 

Source Link

Usage

From source file:com.intel.xdk.device.Device.java

private void registerBatteryChangeReceiver() {

    if (batteryChangeReceiver == null) {

        batteryChangeReceiver = new BroadcastReceiver() {

            @Override/* www . j a  v  a 2 s .  c  o  m*/
            public void onReceive(Context context, Intent intent) {
                int batteryStatus = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                boolean isCharging = batteryStatus == BatteryManager.BATTERY_STATUS_CHARGING
                        || batteryStatus == BatteryManager.BATTERY_STATUS_FULL;

                if (isCharging) {
                    if (wl == null) {
                        aquireWakeLock();
                    }
                } else {
                    if (wl != null) {
                        wl.release();
                        wl = null;
                    }
                }
            }

        };
    }

    activity.registerReceiver(batteryChangeReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

From source file:com.droid.app.fotobot.FotoBot.java

public void sendSMS(String phoneNumber, String message) {
    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";

    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);

    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);

    //---when the SMS has been sent---
    registerReceiver(new BroadcastReceiver() {
        @Override/*ww w  . j  a v a2s  .c  om*/
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS sent", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }, new IntentFilter(SENT));

    //---when the SMS has been delivered---
    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_SHORT).show();
                break;
            case Activity.RESULT_CANCELED:
                Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }, new IntentFilter(DELIVERED));

    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}

From source file:de.ub0r.android.websms.WebSMS.java

/**
 * Send a command as broadcast./*  w  ww. j  a  v  a 2s.com*/
 *
 * @param context   Current context
 * @param connector {@link ConnectorSpec}
 * @param command   {@link ConnectorCommand}
 */
static void runCommand(final Context context, final ConnectorSpec connector, final ConnectorCommand command) {
    connector.setErrorMessage((String) null);
    final Intent intent = command.setToIntent(null);
    short t = command.getType();
    boolean sendOrdered = false;
    switch (t) {
    case ConnectorCommand.TYPE_BOOTSTRAP:
        sendOrdered = true;
        intent.setAction(connector.getPackage() + Connector.ACTION_RUN_BOOTSTRAP);
        connector.addStatus(ConnectorSpec.STATUS_BOOTSTRAPPING);
        break;
    case ConnectorCommand.TYPE_SEND:
        sendOrdered = true;
        intent.setAction(connector.getPackage() + Connector.ACTION_RUN_SEND);
        connector.setToIntent(intent);
        connector.addStatus(ConnectorSpec.STATUS_SENDING);
        if (command.getResendCount() == 0) {
            WebSMSReceiver.saveMessage(me, connector, command, WebSMSReceiver.MESSAGE_TYPE_DRAFT);
        }
        break;
    case ConnectorCommand.TYPE_UPDATE:
        intent.setAction(connector.getPackage() + Connector.ACTION_RUN_UPDATE);
        connector.addStatus(ConnectorSpec.STATUS_UPDATING);
        break;
    default:
        break;
    }
    updateProgressBar();
    intent.setFlags(intent.getFlags() | Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    Log.d(TAG, "send broadcast: " + intent.getAction());
    if (sendOrdered) {
        context.sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
            @Override
            public void onReceive(final Context context, final Intent intent) {
                if (this.getResultCode() != Activity.RESULT_OK) {
                    ConnectorCommand command = new ConnectorCommand(intent);
                    ConnectorSpec specs = new ConnectorSpec(intent);
                    specs.setErrorMessage(// TODO: localize
                            "Connector did not react on message");
                    WebSMSReceiver.handleSendCommand(context, specs, command);
                }
            }
        }, null, Activity.RESULT_CANCELED, null, null);
    } else {
        context.sendBroadcast(intent);
    }
}

From source file:com.hichinaschool.flashcards.anki.CardBrowser.java

/**
 * Show/dismiss dialog when sd card is ejected/remounted (collection is saved by SdCardReceiver)
 *//*w w w . j av a 2 s  .c o m*/
private void registerExternalStorageListener() {
    if (mUnmountReceiver == null) {
        mUnmountReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(SdCardReceiver.MEDIA_EJECT)) {
                    finish();
                }
            }
        };
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SdCardReceiver.MEDIA_EJECT);
        registerReceiver(mUnmountReceiver, iFilter);
    }
}

From source file:com.eveningoutpost.dexdrip.Home.java

@Override
protected void onResume() {
    xdrip.checkForcedEnglish(xdrip.getAppContext());
    super.onResume();
    checkEula();/*  w w  w  .  jav a  2 s .  c  o  m*/
    set_is_follower();
    _broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context ctx, Intent intent) {
            if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0) {
                updateCurrentBgInfo("time tick");
            }
        }
    };
    newDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context ctx, Intent intent) {
            holdViewport.set(0, 0, 0, 0);
            updateCurrentBgInfo("new data");
        }
    };
    registerReceiver(_broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
    registerReceiver(newDataReceiver, new IntentFilter(Intents.ACTION_NEW_BG_ESTIMATE_NO_DATA));
    holdViewport.set(0, 0, 0, 0);

    if (invalidateMenu) {
        invalidateOptionsMenu();
        invalidateMenu = false;
    }
    activityVisible = true;
    updateCurrentBgInfo("generic on resume");

    if (!JoH.getWifiSleepPolicyNever()) {
        if (JoH.ratelimit("policy-never", 3600)) {
            if (getPreferencesLong("wifi_warning_never", 0) == 0) {
                if (!JoH.isMobileDataOrEthernetConnected()) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("WiFi Sleep Policy Issue");
                    builder.setMessage(
                            "Your WiFi is set to sleep when the phone screen is off.\n\nThis may cause problems if you don't have cellular data or have devices on your local network.\n\nWould you like to go to the settings page to set:\n\nAlways Keep WiFi on during Sleep?");

                    builder.setNeutralButton("Maybe Later", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    builder.setPositiveButton("YES, Do it", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            toast("Recommend that you change WiFi to always be on during sleep");
                            startActivity(new Intent(Settings.ACTION_WIFI_IP_SETTINGS));

                        }
                    });

                    builder.setNegativeButton("NO, Never", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            setPreferencesLong("wifi_warning_never", (long) JoH.ts());
                        }
                    });

                    AlertDialog alert = builder.create();
                    alert.show();

                }
            }
        }
    }

    if (NFCReaderX.useNFC()) {
        NFCReaderX.doNFC(this);
    } else {
        NFCReaderX.disableNFC(this);
    }

    if (get_follower() || get_master()) {
        GcmActivity.checkSync(this);
    }
}

From source file:com.scoreflex.Scoreflex.java

/**
 * Method to call on your onCreate method to handle the Scoreflex
 * notification, it must be added to the Activity implementation of the
 * class you gave to/*  w  w  w .j a  v a 2s  .c  o  m*/
 * {@link #onBroadcastReceived(Context, Intent, int, Class)} (must be called
 * after Scoreflex.initialize(). As follow:
 *
 * <pre>
 * <code>
 * protected void onCreate(Bundle savedInstance) {
 *    Scoreflex.onCreateMainActivity(this, getIntent());
 * }
 * </code>
 * </pre>
 *
 * @param activity
 *            The current activity.
 * @param intent
 *            The intent the activity received.
 * @param useActivityForViews
 *            Set if scoreflex views should be presented as separate activities
 *
 * @return <code>true</code> if handled, <code>false</code> otherwise.
 */
public static boolean onCreateMainActivity(final Activity activity, Intent intent,
        final boolean useActivityForViews) {
    if (intent.hasExtra(Scoreflex.NOTIFICATION_EXTRA_KEY)) {
        String notificationString = intent.getStringExtra(Scoreflex.NOTIFICATION_EXTRA_KEY);

        try {
            JSONObject notification = new JSONObject(notificationString);
            JSONObject data = notification.getJSONObject("data");
            String resource = null;
            Scoreflex.RequestParams parameters = null;
            int code = notification.getInt("code");
            Scoreflex.RequestParams trackParams = new Scoreflex.RequestParams();
            trackParams.put("code", Integer.toString(code));
            Scoreflex.postEventually("/notifications/track", trackParams, null);
            if (NOTIFICATION_TYPE_CHALLENGE_INVITATION == code
                    || NOTIFICATION_TYPE_YOUR_TURN_IN_CHALLENGE == code
                    || NOTIFICATION_TYPE_CHALLENGE_ENDED == code) {
                resource = "/web/challenges/instances/" + data.getString("challengeInstanceId");
            } else if (NOTIFICATION_TYPE_FRIEND_JOINED_GAME == code) {
                resource = "/web/players/" + data.getString("friendId");
            } else if (NOTIFICATION_TYPE_FRIEND_BEAT_YOUR_HIGHSCORE == code) {
                parameters = new RequestParams();
                parameters.put("friendsOnly", "true");
                parameters.put("focus", data.getString("friendId"));
                resource = "/web/leaderboards/" + data.getString("leaderboardId");
            } else if (NOTIFICATION_TYPE_PLAYER_LEVEL_CHANGED == code) {
                resource = "/web/players/me";
            }
            if (isInitialized()) {
                showView(activity, resource, parameters, useActivityForViews);
            } else {
                final String finalResource = resource;
                final Scoreflex.RequestParams params = parameters;
                BroadcastReceiver receiver = new BroadcastReceiver() {

                    @Override
                    public void onReceive(Context context, Intent intent) {
                        showView(activity, finalResource, params, useActivityForViews);
                        LocalBroadcastManager.getInstance(activity).unregisterReceiver(this);
                    }
                };

                IntentFilter filter = new IntentFilter(Scoreflex.INTENT_SCOREFLEX_INTIALIZED);
                LocalBroadcastManager.getInstance(activity).registerReceiver(receiver, filter);
            }
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    return false;
}

From source file:com.ichi2.anki.DeckPicker.java

/**
 * Show a message when the SD card is ejected
 */// w  ww  .j  a v a2  s  . c o  m
private void registerExternalStorageListener() {
    if (mUnmountReceiver == null) {
        mUnmountReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(SdCardReceiver.MEDIA_EJECT)) {
                    onSdCardNotMounted();
                } else if (intent.getAction().equals(SdCardReceiver.MEDIA_MOUNT)) {
                    restartActivity();
                }
            }
        };
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SdCardReceiver.MEDIA_EJECT);
        iFilter.addAction(SdCardReceiver.MEDIA_MOUNT);
        registerReceiver(mUnmountReceiver, iFilter);
    }
}

From source file:com.citrus.sdk.CitrusClient.java

private <T> void registerReceiver(final Callback<T> callback, IntentFilter intentFilter) {
    paymentEventReceiver = new BroadcastReceiver() {
        @Override/*www. j a v  a2 s . c o m*/
        public void onReceive(Context context, Intent intent) {
            unregisterReceiver(this);

            TransactionResponse transactionResponse = intent
                    .getParcelableExtra(Constants.INTENT_EXTRA_TRANSACTION_RESPONSE);
            if (transactionResponse != null) {
                TransactionResponse.TransactionStatus transactionStatus = transactionResponse
                        .getTransactionStatus();
                Status status = null;

                if (transactionStatus != null) {
                    switch (transactionStatus) {

                    case SUCCESSFUL:
                        status = Status.SUCCESSFUL;
                        break;
                    case FAILED:
                        status = Status.FAILED;
                        break;
                    case CANCELLED:
                        status = Status.CANCELLED;
                        break;
                    case PG_REJECTED:
                        status = Status.PG_REJECTED;
                        break;
                    }
                }
                if (transactionStatus == TransactionResponse.TransactionStatus.SUCCESSFUL) {
                    sendResponse(callback, transactionResponse);
                } else {
                    sendError(callback, new CitrusError(transactionResponse.getMessage(), status));
                }
            }
        }
    };

    LocalBroadcastManager.getInstance(mContext).registerReceiver(paymentEventReceiver, intentFilter);
}

From source file:com.hichinaschool.flashcards.anki.DeckPicker.java

/**
 * Show/dismiss dialog when sd card is ejected/remounted (collection is saved by SdCardReceiver)
 *///from   ww w . j  a  v a  2 s . co m
private void registerExternalStorageListener() {
    if (mUnmountReceiver == null) {
        mUnmountReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (AnkiDroidApp.getSharedPrefs(getBaseContext()).getBoolean("internalMemory", false)) {
                    return;
                }
                if (intent.getAction().equals(SdCardReceiver.MEDIA_EJECT)) {
                    showDialog(DIALOG_SD_CARD_NOT_MOUNTED);
                } else if (intent.getAction().equals(SdCardReceiver.MEDIA_MOUNT)) {
                    if (mNotMountedDialog != null && mNotMountedDialog.isShowing()) {
                        mNotMountedDialog.dismiss();
                    }
                    loadCollection();
                }
            }
        };
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SdCardReceiver.MEDIA_EJECT);
        iFilter.addAction(SdCardReceiver.MEDIA_MOUNT);
        registerReceiver(mUnmountReceiver, iFilter);
    }
}