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.easemob.chatuidemo.activity.MainActivity.java

/**
 * ??/* w ww.  j  av  a2s  .c  om*/
 */
private void registerInternalDebugReceiver() {
    internalDebugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            MyApplication.getInstance().logout(new EMCallBack() {

                @Override
                public void onSuccess() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            // ??
                            finish();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));

                        }
                    });
                }

                @Override
                public void onProgress(int progress, String status) {
                }

                @Override
                public void onError(int code, String message) {
                }
            });
        }
    };
    IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug");
    registerReceiver(internalDebugReceiver, filter);
}

From source file:com.anp.bdmt.MainActivity.java

/**
 * LocalBroadcast  ?. ?? ??  READY, GENERATING, COMPLETE ? ?
 * UI?  .//from ww  w .  ja v  a  2s .c  o m
 */
public void registBroadcastReceiver() {
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(QuickstartPreferences.REGISTRATION_READY)) {
                // ? READY? 
                Log.i(TAG, "regist READY");
            } else if (action.equals(QuickstartPreferences.REGISTRATION_GENERATING)) {
                // ? GENERATING? 
                Log.i(TAG, "regist GENERATING");
            } else if (action.equals(QuickstartPreferences.REGISTRATION_COMPLETE)) {
                // ? COMPLETE? 
                String token = intent.getStringExtra("token");

                TOKEN_ID = token;

                Log.i(TAG, "token: " + token);
                getTokenId(token);
            } else if (action.equals(QuickstartPreferences.REGISTRATION_ALREADY)) {
                Log.i(TAG, "regist Already");
            }

        }
    };
}

From source file:com.moez.QKSMS.mmssms.Transaction.java

private void trySending(final APN apns, final byte[] bytesToSend, final int numRetries) {
    try {/*w  ww  . j  av a2s  .c o m*/
        IntentFilter filter = new IntentFilter();
        filter.addAction(ProgressCallbackEntity.PROGRESS_STATUS_ACTION);
        BroadcastReceiver receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                int progress = intent.getIntExtra("progress", -3);
                if (LOCAL_LOGV)
                    Log.v(TAG, "progress: " + progress);

                // send progress broadcast to update ui if desired...
                Intent progressIntent = new Intent(MMS_PROGRESS);
                progressIntent.putExtra("progress", progress);
                context.sendBroadcast(progressIntent);

                if (progress == ProgressCallbackEntity.PROGRESS_COMPLETE) {
                    if (saveMessage) {
                        Cursor query = context.getContentResolver().query(Uri.parse("content://mms"),
                                new String[] { "_id" }, null, null, "date desc");
                        if (query != null && query.moveToFirst()) {
                            String id = query.getString(query.getColumnIndex("_id"));
                            query.close();

                            // move to the sent box
                            ContentValues values = new ContentValues();
                            values.put("msg_box", 2);
                            String where = "_id" + " = '" + id + "'";
                            context.getContentResolver().update(Uri.parse("content://mms"), values, where,
                                    null);
                        }
                    }

                    context.sendBroadcast(new Intent(REFRESH));

                    try {
                        context.unregisterReceiver(this);
                    } catch (Exception e) {
                        /* Receiver not registered */ }

                    // give everything time to finish up, may help the abort being shown after the progress is already 100
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mConnMgr.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE_MMS, "enableMMS");
                            if (settings.getWifiMmsFix()) {
                                reinstateWifi();
                            }
                        }
                    }, 1000);
                } else if (progress == ProgressCallbackEntity.PROGRESS_ABORT) {
                    // This seems to get called only after the progress has reached 100 and then something else goes wrong, so here we will try and send again and see if it works
                    if (LOCAL_LOGV)
                        Log.v(TAG, "sending aborted for some reason...");
                    context.unregisterReceiver(this);

                    if (numRetries < NUM_RETRIES) {
                        // sleep and try again in three seconds to see if that give wifi and mobile data a chance to toggle in time
                        try {
                            Thread.sleep(3000);
                        } catch (Exception f) {

                        }

                        if (settings.getWifiMmsFix()) {
                            sendMMS(bytesToSend);
                        } else {
                            sendMMSWiFi(bytesToSend);
                        }
                    } else {
                        markMmsFailed();
                    }
                }
            }

        };

        context.registerReceiver(receiver, filter);

        // This is where the actual post request is made to send the bytes we previously created through the given apns
        if (LOCAL_LOGV)
            Log.v(TAG, "attempt: " + numRetries);
        Utils.ensureRouteToHost(context, apns.MMSCenterUrl, apns.MMSProxy);
        HttpUtils.httpConnection(context, 4444L, apns.MMSCenterUrl, bytesToSend, HttpUtils.HTTP_POST_METHOD,
                !TextUtils.isEmpty(apns.MMSProxy), apns.MMSProxy, Integer.parseInt(apns.MMSPort));
    } catch (IOException e) {
        if (LOCAL_LOGV)
            Log.v(TAG, "some type of error happened when actually sending maybe?");
        Log.e(TAG, "exception thrown", e);

        if (numRetries < NUM_RETRIES) {
            // sleep and try again in three seconds to see if that give wifi and mobile data a chance to toggle in time
            try {
                Thread.sleep(3000);
            } catch (Exception f) {

            }

            trySending(apns, bytesToSend, numRetries + 1);
        } else {
            markMmsFailed();
        }
    }
}

From source file:com.easemob.chatuidemo.activity.MainActivity.java

public void setXG() {
    BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override/*from   www  .j  a  va2 s .  c o  m*/
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            System.out.println("hahahhahahah");
        }

    };
    IntentFilter intent = new IntentFilter();
    intent.addAction("bobo.com");
    this.registerReceiver(receiver, intent);
    Handler handler = new HandlerExtension(this);
    m = handler.obtainMessage();

    XGPushManager.registerPush(getApplicationContext(), Preferences.getUserName(), new XGIOperateCallback() {

        @Override
        public void onSuccess(Object arg0, int arg1) {
            // TODO Auto-generated method stub
            System.out.println("?");
            m.sendToTarget();
        }

        @Override
        public void onFail(Object arg0, int arg1, String arg2) {
            // TODO Auto-generated method stub
            m.sendToTarget();
            System.out.println("");
        }
    });
}

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

/**
 * Show/dismiss dialog when sd card is ejected/remounted (collection is saved by SdCardReceiver)
 *///  ww  w . ja  va 2s. 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)) {
                    finishWithoutAnimation();
                }
            }
        };
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SdCardReceiver.MEDIA_EJECT);
        registerReceiver(mUnmountReceiver, iFilter);
    }
}

From source file:cn.gen.superwechat.activity.MainActivity.java

/**
 * ??//  w  w  w.j a  va2s.  c  om
 */
private void registerInternalDebugReceiver() {
    internalDebugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            DemoHXSDKHelper.getInstance().logout(true, new EMCallBack() {

                @Override
                public void onSuccess() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            // ??
                            finish();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));

                        }
                    });
                }

                @Override
                public void onProgress(int progress, String status) {
                }

                @Override
                public void onError(int code, String message) {
                }
            });
        }
    };
    IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug");
    registerReceiver(internalDebugReceiver, filter);
}

From source file:com.partypoker.poker.engagement.reach.EngagementReachAgent.java

/**
 * Try to notify the content to the user.
 * @param content reach content.//from  w  ww.  j a v a  2  s.  c  o m
 * @param replaySystemNotifications true iff system notifications must be replayed.
 * @throws RuntimeException if an error occurs.
 */
private void notifyContent(final EngagementReachContent content, boolean replaySystemNotifications)
        throws RuntimeException {
    /* Check expiry */
    final long localId = content.getLocalId();
    if (content.hasExpired()) {
        /* Delete */
        deleteContent(content);
        return;
    }

    /* If datapush, just broadcast, can be done in parallel with another content */
    final Intent intent = content.getIntent();
    if (content instanceof com.microsoft.azure.engagement.reach.EngagementDataPush) {
        /* Delay data push until DLC completes */
        if (!checkRequestDlc(content))
            return;

        /* If it's a datapush it may already be in the process of broadcasting. */
        if (!mPendingDataPushes.add(localId))
            return;

        /* Broadcast intent */
        final com.microsoft.azure.engagement.reach.EngagementDataPush dataPush = (EngagementDataPush) content;
        intent.setPackage(mContext.getPackageName());
        mContext.sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                /* The last broadcast receiver to set a defined result wins (to determine which result). */
                switch (getResultCode()) {
                case RESULT_OK:
                    dataPush.actionContent(context);
                    break;

                case RESULT_CANCELED:
                    dataPush.exitContent(context);
                    break;

                default:
                    dataPush.dropContent(context);
                }

                /* Clean broadcast state */
                mPendingDataPushes.remove(localId);
            }
        }, null, RESULT_UNDEFINED, null, null);

        /* Datapush processed */
        return;
    }

    /* If notification has pending downloadable content, delay */
    if (content.hasNotificationDLC() && !checkRequestDlc(content))
        return;

    /* Don't notify in-app if we are already notifying in app or showing a content */
    if (mState != State.IDLE && !content.isSystemNotification())
        return;

    /* Don't process again a pending notification */
    if (mPendingNotifications.contains(localId))
        return;

    /* Not an interactive content, exit (but there is no other type left, this is just a cast guard) */
    if (!(content instanceof EngagementReachInteractiveContent))
        return;
    EngagementReachInteractiveContent iContent = (EngagementReachInteractiveContent) content;

    /* Don't replay system notification unless told otherwise. */
    if (!replaySystemNotifications && iContent.isSystemNotification()
            && iContent.getNotificationLastDisplayedDate() != null
            && iContent.getNotificationLastDisplayedDate() > mAppLastUpdateTime)
        return;

    /* Check if the content can be notified in the current context (behavior) */
    if (!iContent.canNotify(sActivityManager.getCurrentActivityAlias()))
        return;

    /* If there is a show intent */
    if (intent != null)
        filterIntentWithCategory(intent);

    /* Delegate notification */
    Boolean notifierResult = getNotifier(content).handleNotification(iContent);

    /* Check if notifier rejected content notification for now */
    if (Boolean.FALSE.equals(notifierResult))

        /* The notifier rejected the content, nothing more to do */
        return;

    /* Cache content if accepted, it will most likely be used again soon for the next steps. */
    mContentCache.put(localId, content);

    /*
     * If notifier did not return null (e.g. returned true, meaning actually accepted the content),
     * we assume the notification is correctly displayed.
     */
    if (Boolean.TRUE.equals(notifierResult)) {
        /* Report displayed feedback */
        iContent.displayNotification(mContext);

        /* Track in-app content life cycle: one at a time */
        if (!iContent.isSystemNotification())
            mState = State.NOTIFYING_IN_APP;
    }

    /* Track pending notifications to avoid re-processing them every time we change activity. */
    if (notifierResult == null)
        mPendingNotifications.add(localId);
}

From source file:com.csipsimple.service.SipService.java

private void registerServiceBroadcasts() {
    if (serviceReceiver == null) {
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(SipManager.ACTION_DEFER_OUTGOING_UNREGISTER);
        intentfilter.addAction(SipManager.ACTION_OUTGOING_UNREGISTER);
        serviceReceiver = new BroadcastReceiver() {
            @Override//ww  w .  ja v a 2s .  co m
            public void onReceive(Context context, Intent intent) {
                Log.d("checkIntent", "intent:" + intent.getAction());
                String action = intent.getAction();
                if (action.equals(SipManager.ACTION_OUTGOING_UNREGISTER)) {
                    unregisterForOutgoing(
                            (ComponentName) intent.getParcelableExtra(SipManager.EXTRA_OUTGOING_ACTIVITY));
                } else if (action.equals(SipManager.ACTION_DEFER_OUTGOING_UNREGISTER)) {
                    deferUnregisterForOutgoing(
                            (ComponentName) intent.getParcelableExtra(SipManager.EXTRA_OUTGOING_ACTIVITY));
                }
            }

        };
        registerReceiver(serviceReceiver, intentfilter);
    }
}

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

private void registerScreenStatusReceiver() {

    if (screenStatusReceiver == null) {
        //Listener to the screen unlock event.

        screenStatusReceiver = new BroadcastReceiver() {

            @Override/*  www.j  a v  a 2s  .c  om*/
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                    Log.d("screen_on", "Screen is on.");
                } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                    Log.d("screen_lock", "Screen is off");
                    String js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.pause');e.success=true;document.dispatchEvent(e);";
                    injectJS(js);
                } else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
                    Log.d("user_present", "User is present.");
                    String js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.device.continue');e.success=true;document.dispatchEvent(e);";
                    injectJS(js);
                }

            }

        };
    }
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    activity.registerReceiver(screenStatusReceiver, filter);
}

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

/**
 *  ? ?. ?  ,     battery_level./* www.java 2  s  .com*/
 */
public void batteryLevel() {

    BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            //context.unregisterReceiver(this);

            int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            battery_temperature = ((float) intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)) / 10.0f;
            battery_level = -1;
            if (rawlevel >= 0 && scale > 0) {
                battery_level = (rawlevel * 100) / scale;
            }

            //   int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
            //  isPlugged = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
            //   if (VERSION.SDK_INT > VERSION_CODES.JELLY_BEAN) {
            //       isPlugged = isPlugged || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;
            //   }

        }
    };

    IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryLevelReceiver, batteryLevelFilter);

}