android.content.BroadcastReceiver Java Examples

The following examples show how to use android.content.BroadcastReceiver. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LeftMenuFragment.java    From iBeebo with GNU General Public License v3.0 7 votes vote down vote up
private boolean showHomePage(boolean reset) {
    if (currentIndex == HOME_INDEX && !reset) {
        return true;
    }
    currentIndex = HOME_INDEX;
    if (Utility.isDevicePort() && !reset) {
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(this);
                if (currentIndex == HOME_INDEX) {
                    mToolbar.setTitle(R.string.weibo_home_page);
                    showHomePageImp();
                }

            }
        };
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter(AppEventAction.SLIDING_MENU_CLOSED_BROADCAST));
    } else {
        showHomePageImp();

    }
    return false;
}
 
Example #2
Source File: LaunchAnalyzerReceiverTest.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 6 votes vote down vote up
@Test
public void onReceive() throws Exception {

    //one
    ShadowApplication application = ShadowApplication.getInstance();
    Intent intent = new Intent(ACTION);
    boolean result = application.hasReceiverForIntent(intent);
    assertTrue(result);

    //only one
    List<BroadcastReceiver> receivers = application.getReceiversForIntent(intent);
    assertEquals(1,receivers.size());

    //test onReceive
    intent.putExtra("c","off");
    BroadcastReceiver targetReceiver = receivers.get(0);
    targetReceiver.onReceive(application.getApplicationContext(),intent);

    Intent serviceIntent = application.getNextStoppedService();
    assertEquals(serviceIntent.getComponent().getClassName(),AnalyzerService.class.getCanonicalName());
}
 
Example #3
Source File: AndroidOperationTube.java    From java-unified-sdk with Apache License 2.0 6 votes vote down vote up
public boolean queryOnlineClients(String self, List<String> clients, final AVIMOnlineClientsCallback callback) {
  Map<String, Object> params = new HashMap<String, Object>();
  params.put(Conversation.PARAM_ONLINE_CLIENTS, clients);

  BroadcastReceiver receiver = null;
  if (callback != null) {
    receiver = new AVIMBaseBroadcastReceiver(callback) {
      @Override
      public void execute(Map<String, Object> intentResult, Throwable error) {
        if (error != null) {
          callback.internalDone(null, AVIMException.wrapperAVException(error));
        } else {
          List<String> onlineClients = null;
          if (null != intentResult && intentResult.containsKey(Conversation.callbackOnlineClients)) {
            onlineClients = (List<String>) intentResult.get(Conversation.callbackOnlineClients);
          }
          callback.internalDone(onlineClients, null);
        }
      }
    };
  }

  return this.sendClientCMDToPushService(self, JSON.toJSONString(params), receiver, AVIMOperation.CLIENT_ONLINE_QUERY);
}
 
Example #4
Source File: WifiListActivity.java    From WiFiKeyShare with GNU General Public License v3.0 6 votes vote down vote up
void initializeWifiStateChangeListener() {
    wifiStateChangeBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
                final boolean isConnected = intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);

                if (isConnected) {
                    if (waitingForWifiToTurnOn) {
                        (new WifiListTask()).execute();
                    }
                }
            }
        }
    };
}
 
Example #5
Source File: PendingResultData.java    From container with GNU General Public License v3.0 5 votes vote down vote up
public PendingResultData(BroadcastReceiver.PendingResult result) {
    if (mirror.android.content.BroadcastReceiver.PendingResultMNC.ctor != null) {
        mType = mirror.android.content.BroadcastReceiver.PendingResultMNC.mType.get(result);
        mOrderedHint = mirror.android.content.BroadcastReceiver.PendingResultMNC.mOrderedHint.get(result);
        mInitialStickyHint = mirror.android.content.BroadcastReceiver.PendingResultMNC.mInitialStickyHint.get(result);
        mToken = mirror.android.content.BroadcastReceiver.PendingResultMNC.mToken.get(result);
        mSendingUser = mirror.android.content.BroadcastReceiver.PendingResultMNC.mSendingUser.get(result);
        mFlags = mirror.android.content.BroadcastReceiver.PendingResultMNC.mFlags.get(result);
        mResultCode = mirror.android.content.BroadcastReceiver.PendingResultMNC.mResultCode.get(result);
        mResultData = mirror.android.content.BroadcastReceiver.PendingResultMNC.mResultData.get(result);
        mResultExtras = mirror.android.content.BroadcastReceiver.PendingResultMNC.mResultExtras.get(result);
        mAbortBroadcast = mirror.android.content.BroadcastReceiver.PendingResultMNC.mAbortBroadcast.get(result);
        mFinished = mirror.android.content.BroadcastReceiver.PendingResultMNC.mFinished.get(result);
    } else if (mirror.android.content.BroadcastReceiver.PendingResultJBMR1.ctor != null) {
        mType = mirror.android.content.BroadcastReceiver.PendingResultJBMR1.mType.get(result);
        mOrderedHint = mirror.android.content.BroadcastReceiver.PendingResultJBMR1.mOrderedHint.get(result);
        mInitialStickyHint = mirror.android.content.BroadcastReceiver.PendingResultJBMR1.mInitialStickyHint.get(result);
        mToken = mirror.android.content.BroadcastReceiver.PendingResultJBMR1.mToken.get(result);
        mSendingUser = mirror.android.content.BroadcastReceiver.PendingResultJBMR1.mSendingUser.get(result);
        mResultCode = mirror.android.content.BroadcastReceiver.PendingResultJBMR1.mResultCode.get(result);
        mResultData = mirror.android.content.BroadcastReceiver.PendingResultJBMR1.mResultData.get(result);
        mResultExtras = mirror.android.content.BroadcastReceiver.PendingResultJBMR1.mResultExtras.get(result);
        mAbortBroadcast = mirror.android.content.BroadcastReceiver.PendingResultJBMR1.mAbortBroadcast.get(result);
        mFinished = mirror.android.content.BroadcastReceiver.PendingResultJBMR1.mFinished.get(result);
    } else {
        mType = mirror.android.content.BroadcastReceiver.PendingResult.mType.get(result);
        mOrderedHint = mirror.android.content.BroadcastReceiver.PendingResult.mOrderedHint.get(result);
        mInitialStickyHint = mirror.android.content.BroadcastReceiver.PendingResult.mInitialStickyHint.get(result);
        mToken = mirror.android.content.BroadcastReceiver.PendingResult.mToken.get(result);
        mResultCode = mirror.android.content.BroadcastReceiver.PendingResult.mResultCode.get(result);
        mResultData = mirror.android.content.BroadcastReceiver.PendingResult.mResultData.get(result);
        mResultExtras = mirror.android.content.BroadcastReceiver.PendingResult.mResultExtras.get(result);
        mAbortBroadcast = mirror.android.content.BroadcastReceiver.PendingResult.mAbortBroadcast.get(result);
        mFinished = mirror.android.content.BroadcastReceiver.PendingResult.mFinished.get(result);
    }
}
 
Example #6
Source File: ContextImpl.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void unregisterReceiver(BroadcastReceiver receiver) {
    if (mPackageInfo != null) {
        IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher(
                getOuterContext(), receiver);
        try {
            ActivityManager.getService().unregisterReceiver(rd);
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    } else {
        throw new RuntimeException("Not supported in system context");
    }
}
 
Example #7
Source File: SmsHandlerHook.java    From NekoSMS with GNU General Public License v3.0 5 votes vote down vote up
private void hookDispatchIntent23(XC_LoadPackage.LoadPackageParam lpparam) {
    Xlog.i("Hooking dispatchIntent() for Android v23+");
    XposedHelpers.findAndHookMethod(SMS_HANDLER_CLASS, lpparam.classLoader, "dispatchIntent",
        /*         intent */ Intent.class,
        /*     permission */ String.class,
        /*          appOp */ int.class,
        /*           opts */ Bundle.class,
        /* resultReceiver */ BroadcastReceiver.class,
        /*           user */ UserHandle.class,
        new DispatchIntentHook(4));
}
 
Example #8
Source File: BinaryWatchFaceService.java    From WearBinaryWatchFace with Apache License 2.0 5 votes vote down vote up
private void init() {
    setWatchFaceStyle(new WatchFaceStyle.Builder(BinaryWatchFaceService.this)
            .setCardPeekMode(WatchFaceStyle.PEEK_MODE_SHORT)
            .setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
            .setStatusBarGravity(Gravity.LEFT | Gravity.TOP)
            .setHotwordIndicatorGravity(Gravity.RIGHT | Gravity.TOP)
            .setShowSystemUiTime(false)
            .build());

    Resources resources = BinaryWatchFaceService.this.getResources();
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(BinaryWatchFaceService.this);

    mYOffset = resources.getDimension(R.dimen.digital_y_offset);

    mBackgroundPaint = new Paint();
    mBackgroundPaint.setColor(mInteractiveBackgroundColor);

    interactiveActiveDotPaint = new Paint();
    interactiveActiveDotPaint.setColor(preferences.getInt(getResources().getString(R.string.pref_key_dot_color), getResources().getColor(R.color.circle_default)));
    interactiveActiveDotPaint.setAntiAlias(true);

    ambientActiveDotPaint = new Paint();
    ambientActiveDotPaint.setColor(getResources().getColor(R.color.circle_dimmed_active));
    ambientActiveDotPaint.setAntiAlias(true);

    inactiveDotColor = new Paint();
    inactiveDotColor.setColor(getResources().getColor(R.color.circle_inactive));
    inactiveDotColor.setAntiAlias(true);

    textPaint = createTextPaint(mInteractiveTextColor, NORMAL_TYPEFACE);

    preferenceChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constants.NEW_CONFIGURATION_RECEIVED.equals(intent.getAction())) {
                interactiveActiveDotPaint.setColor(preferences.getInt(getResources().getString(R.string.pref_key_dot_color), getResources().getColor(R.color.circle_default)));
            }
        }
    };
}
 
Example #9
Source File: SmsHandlerHook.java    From XposedSmsCode with GNU General Public License v3.0 5 votes vote down vote up
private void hookDispatchIntent19(ClassLoader classloader) {
    XLog.d("Hooking dispatchIntent() for Android v19+");
    XposedHelpers.findAndHookMethod(SMS_HANDLER_CLASS, classloader, "dispatchIntent",
            /*         intent */ Intent.class,
            /*     permission */ String.class,
            /*          appOp */ int.class,
            /* resultReceiver */ BroadcastReceiver.class,
            new DispatchIntentHook(3));
}
 
Example #10
Source File: DefaultAppStateRecognizerSetupTest.java    From RxAppState with MIT License 5 votes vote down vote up
@Test
public void registersCallbacks() {
  recognizer.start();

  verify(mockApplication).registerActivityLifecycleCallbacks(any(ActivityLifecycleCallbacks.class));
  verify(mockApplication).registerComponentCallbacks(any(ComponentCallbacks2.class));
  verify(mockApplication).registerReceiver(any(BroadcastReceiver.class), any(IntentFilter.class));
}
 
Example #11
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
        String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler,
        int initialCode, String initialData, Bundle initialExtras) {
    sendOrderedBroadcastAsUser(intent, user, receiverPermission, AppOpsManager.OP_NONE,
            resultReceiver, scheduler, initialCode, initialData, initialExtras);
}
 
Example #12
Source File: FormEntryActivity.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private void registerFormEntryReceiver() {
    //BroadcastReceiver for:
    // a) An unresolvable xpath expression encountered in PollSensorAction.onLocationChanged
    // b) Checking if GPS services are not available
    mLocationServiceIssueReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            context.removeStickyBroadcast(intent);
            badLocationXpath = intent.getStringExtra(PollSensorAction.KEY_UNRESOLVED_XPATH);
            locationRecieverErrorAction = intent.getAction();
        }
    };

    IntentFilter filter = new IntentFilter();
    filter.addAction(PollSensorAction.XPATH_ERROR_ACTION);
    filter.addAction(GeoUtils.ACTION_CHECK_GPS_ENABLED);
    registerReceiver(mLocationServiceIssueReceiver, filter);
}
 
Example #13
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
@Deprecated
public void sendStickyOrderedBroadcast(Intent intent,
        BroadcastReceiver resultReceiver,
        Handler scheduler, int initialCode, String initialData,
        Bundle initialExtras) {
    warnIfCallingFromSystemProcess();
    IIntentReceiver rd = null;
    if (resultReceiver != null) {
        if (mPackageInfo != null) {
            if (scheduler == null) {
                scheduler = mMainThread.getHandler();
            }
            rd = mPackageInfo.getReceiverDispatcher(
                resultReceiver, getOuterContext(), scheduler,
                mMainThread.getInstrumentation(), false);
        } else {
            if (scheduler == null) {
                scheduler = mMainThread.getHandler();
            }
            rd = new LoadedApk.ReceiverDispatcher(
                    resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
        }
    }
    String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
    try {
        intent.prepareToLeaveProcess(this);
        ActivityManager.getService().broadcastIntent(
            mMainThread.getApplicationThread(), intent, resolvedType, rd,
            initialCode, initialData, initialExtras, null,
                AppOpsManager.OP_NONE, null, true, true, getUserId());
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example #14
Source File: InstallReferrerReceiver.java    From tlplib with MIT License 5 votes vote down vote up
private void broadcastEvent(Context context, Intent intent) {
    List<BroadcastReceiver> proxyClasses = getBroadcastReceivers(context, "TLPLibInstallReferrerReceiver");

    for (BroadcastReceiver r : proxyClasses) {
        try {
            r.onReceive(context, intent);
            Log.i(TAG, "Called onReceive on: " + r.getClass().getName());
        }
        catch (Exception e) {
            Log.e(TAG, "Exception calling onReceive: " + e.getMessage());
        }
    }
}
 
Example #15
Source File: KeyguardClockContainerHook.java    From XMiTools with GNU General Public License v3.0 5 votes vote down vote up
private void hookOnAttachedToWindow() {
    findAndHookMethod(mKeyguardClockContainerClass,
            "onAttachedToWindow",
            new MethodHookWrapper() {
                @Override
                protected void before(MethodHookParam param) {
                    FrameLayout clockContainer = (FrameLayout) param.thisObject;
                    ViewParent parent = clockContainer.getParent();
                    XposedHelpers.callMethod(parent, "onAttachedToWindow");

                    IntentFilter filter = new IntentFilter();
                    // filter.addAction("android.intent.action.TIME_TICK");
                    filter.addAction("android.intent.action.TIME_SET");
                    filter.addAction("android.intent.action.TIMEZONE_CHANGED");

                    BroadcastReceiver mIntentReceiver = (BroadcastReceiver) getObjectField(clockContainer, "mIntentReceiver");
                    Object USER_HANDLE_ALL = getStaticObjectField(UserHandle.class, "ALL");
                    Class<?> dependencyClass = findClass(CLASS_DEPENDENCY, mClassLoader);
                    Object TIME_TICK_HANDLER = getStaticObjectField(dependencyClass, "TIME_TICK_HANDLER");
                    Object handler = XposedHelpers.callStaticMethod(dependencyClass, "get", TIME_TICK_HANDLER);

                    callMethod(clockContainer.getContext(),
                            "registerReceiverAsUser",
                            mIntentReceiver,
                            USER_HANDLE_ALL,
                            filter,
                            null,
                            handler);

                    callMethod(clockContainer, "registerDualClockObserver");
                    callMethod(clockContainer, "registerClockPositionObserver");

                    param.setResult(null);
                }
            });
}
 
Example #16
Source File: LocationModule.java    From rn-background-location with MIT License 5 votes vote down vote up
@Override
public void createEventReceiver() {
    mEventReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            LocationCoordinates locationCoordinates = mGson.fromJson(
                    intent.getStringExtra(LOCATION_EVENT_DATA_NAME), LocationCoordinates.class);
            WritableMap eventData = Arguments.createMap();
            eventData.putDouble(
                    LocationForegroundService.JS_LOCATION_LAT_KEY,
                    locationCoordinates.getLatitude());
            eventData.putDouble(
                    LocationForegroundService.JS_LOCATION_LON_KEY,
                    locationCoordinates.getLongitude());
            eventData.putDouble(
                    LocationForegroundService.JS_LOCATION_TIME_KEY,
                    locationCoordinates.getTimestamp());
            // if you actually want to send events to JS side, it needs to be in the "Module"
            sendEventToJS(getReactApplicationContext(),
                    LocationForegroundService.JS_LOCATION_EVENT_NAME, eventData);
        }
    };
}
 
Example #17
Source File: BluetoothAdapterSnippet.java    From mobly-bundled-snippets with Apache License 2.0 5 votes vote down vote up
@Rpc(description = "Cancel ongoing bluetooth discovery.")
public void btCancelDiscovery() throws BluetoothAdapterSnippetException {
    if (!mBluetoothAdapter.isDiscovering()) {
        Log.d("No ongoing bluetooth discovery.");
        return;
    }
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    mIsDiscoveryFinished = false;
    BroadcastReceiver receiver = new BluetoothScanReceiver();
    mContext.registerReceiver(receiver, filter);
    try {
        if (!mBluetoothAdapter.cancelDiscovery()) {
            throw new BluetoothAdapterSnippetException(
                    "Failed to initiate to cancel bluetooth discovery.");
        }
        if (!Utils.waitUntil(() -> mIsDiscoveryFinished, 120)) {
            throw new BluetoothAdapterSnippetException(
                    "Failed to get discovery results after 2 mins, timeout!");
        }
    } finally {
        mContext.unregisterReceiver(receiver);
    }
}
 
Example #18
Source File: MainActivity.java    From budgetto with MIT License 5 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("pl.cyfrogen.budget.ACTION_LOGOUT");
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };
    registerReceiver(receiver, intentFilter);
}
 
Example #19
Source File: PushListActivity.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void configureBroadcastReceiver() {
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updatePushList();
        }
    };
}
 
Example #20
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
public void sendOrderedBroadcast(Intent intent,
        String receiverPermission, BroadcastReceiver resultReceiver,
        Handler scheduler, int initialCode, String initialData,
        Bundle initialExtras) {
    IIntentReceiver rd = null;
    if (resultReceiver != null) {
        if (mPackageInfo != null) {
            if (scheduler == null) {
                scheduler = mMainThread.getHandler();
            }
            rd = mPackageInfo.getReceiverDispatcher(
                resultReceiver, getOuterContext(), scheduler,
                mMainThread.getInstrumentation(), false);
        } else {
            if (scheduler == null) {
                scheduler = mMainThread.getHandler();
            }
            rd = new LoadedApk.ReceiverDispatcher(
                    resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
        }
    }
    String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
    try {
        intent.setAllowFds(false);
        ActivityManagerNative.getDefault().broadcastIntent(
            mMainThread.getApplicationThread(), intent, resolvedType, rd,
            initialCode, initialData, initialExtras, receiverPermission,
            true, false, Binder.getOrigCallingUser());
    } catch (RemoteException e) {
    }
}
 
Example #21
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
        String broadcastPermission, Handler scheduler) {
    throw new ReceiverCallNotAllowedException(
            "IntentReceiver components are not allowed to register to receive intents");
    //ex.fillInStackTrace();
    //Log.e("IntentReceiver", ex.getMessage(), ex);
    //return mContext.registerReceiver(receiver, filter, broadcastPermission,
    //        scheduler);
}
 
Example #22
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
@Deprecated
public void sendStickyOrderedBroadcast(Intent intent,
        BroadcastReceiver resultReceiver,
        Handler scheduler, int initialCode, String initialData,
        Bundle initialExtras) {
    warnIfCallingFromSystemProcess();
    IIntentReceiver rd = null;
    if (resultReceiver != null) {
        if (mPackageInfo != null) {
            if (scheduler == null) {
                scheduler = mMainThread.getHandler();
            }
            rd = mPackageInfo.getReceiverDispatcher(
                resultReceiver, getOuterContext(), scheduler,
                mMainThread.getInstrumentation(), false);
        } else {
            if (scheduler == null) {
                scheduler = mMainThread.getHandler();
            }
            rd = new LoadedApk.ReceiverDispatcher(
                    resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
        }
    }
    String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
    try {
        intent.prepareToLeaveProcess(this);
        ActivityManager.getService().broadcastIntent(
            mMainThread.getApplicationThread(), intent, resolvedType, rd,
            initialCode, initialData, initialExtras, null,
                AppOpsManager.OP_NONE, null, true, true, getUserId());
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example #23
Source File: CoreAndroid.java    From lona with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Listen for telephony events: RINGING, OFFHOOK and IDLE
 * Send these events to all plugins using
 *      CordovaActivity.onMessage("telephone", "ringing" | "offhook" | "idle")
 */
private void initTelephonyReceiver() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    //final CordovaInterface mycordova = this.cordova;
    this.telephonyReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            // If state has changed
            if ((intent != null) && intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
                if (intent.hasExtra(TelephonyManager.EXTRA_STATE)) {
                    String extraData = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                    if (extraData.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                        LOG.i(TAG, "Telephone RINGING");
                        webView.getPluginManager().postMessage("telephone", "ringing");
                    }
                    else if (extraData.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                        LOG.i(TAG, "Telephone OFFHOOK");
                        webView.getPluginManager().postMessage("telephone", "offhook");
                    }
                    else if (extraData.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                        LOG.i(TAG, "Telephone IDLE");
                        webView.getPluginManager().postMessage("telephone", "idle");
                    }
                }
            }
        }
    };

    // Register the receiver
    webView.getContext().registerReceiver(this.telephonyReceiver, intentFilter);
}
 
Example #24
Source File: InstrumentationConnectionTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyBroadcastRegistrationOnlyCalledOnce() {
  instrumentationConnection.init(mockedInstrumentation, mockedFinisher);
  instrumentationConnection.init(mockedInstrumentation, mockedFinisher);
  instrumentationConnection.init(mockedInstrumentation, mockedFinisher);
  instrumentationConnection.init(mockedInstrumentation, mockedFinisher);

  // verify registerReceiver called only once
  ArgumentCaptor<BroadcastReceiver> brArg = ArgumentCaptor.forClass(BroadcastReceiver.class);
  ArgumentCaptor<IntentFilter> ifArg = ArgumentCaptor.forClass(IntentFilter.class);
  verify(mockedContext).registerReceiver(brArg.capture(), ifArg.capture());
  assertEquals(instrumentationConnection.messengerReceiver, brArg.getValue());
  assertEquals(InstrumentationConnection.BROADCAST_FILTER, ifArg.getValue().getAction(0));
}
 
Example #25
Source File: CoreAndroid.java    From cordova-plugin-app-update-demo with MIT License 5 votes vote down vote up
/**
 * Listen for telephony events: RINGING, OFFHOOK and IDLE
 * Send these events to all plugins using
 *      CordovaActivity.onMessage("telephone", "ringing" | "offhook" | "idle")
 */
private void initTelephonyReceiver() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    //final CordovaInterface mycordova = this.cordova;
    this.telephonyReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            // If state has changed
            if ((intent != null) && intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
                if (intent.hasExtra(TelephonyManager.EXTRA_STATE)) {
                    String extraData = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                    if (extraData.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                        LOG.i(TAG, "Telephone RINGING");
                        webView.getPluginManager().postMessage("telephone", "ringing");
                    }
                    else if (extraData.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                        LOG.i(TAG, "Telephone OFFHOOK");
                        webView.getPluginManager().postMessage("telephone", "offhook");
                    }
                    else if (extraData.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                        LOG.i(TAG, "Telephone IDLE");
                        webView.getPluginManager().postMessage("telephone", "idle");
                    }
                }
            }
        }
    };

    // Register the receiver
    webView.getContext().registerReceiver(this.telephonyReceiver, intentFilter);
}
 
Example #26
Source File: ReceiverHelper.java    From understand-plugin-framework with Apache License 2.0 5 votes vote down vote up
public static void preLoadReceiver(Context context, File apk) throws Exception {
    parserReceivers(apk);

    ClassLoader cl = null;
    for (ActivityInfo activityInfo : ReceiverHelper.sCache.keySet()) {
        Log.i(TAG, "preload receiver:" + activityInfo.name);
        List<? extends IntentFilter> intentFilters = ReceiverHelper.sCache.get(activityInfo);
        if (cl == null) {
            cl = CustomClassLoader.getPluginClassLoader(apk, activityInfo.packageName);
        }

        // 把解析出来的每一个静态Receiver都注册为动态的
        for (IntentFilter intentFilter : intentFilters) {
            BroadcastReceiver receiver = (BroadcastReceiver) cl.loadClass(activityInfo.name).newInstance();
            context.registerReceiver(receiver, intentFilter);
        }
    }
}
 
Example #27
Source File: Texting.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Callback method to handle the result of attempting to send a message. 
 * Each message is assigned a Broadcast receiver that is notified by 
 * the phone's radio regarding the status of the sent message. The 
 * receivers call this method.  (See transmitMessage() method below.)
 * 
 * @param context
 *            The context in which the calling BroadcastReceiver is running.
 * @param receiver
 *            Currently unused. Intended as a special BroadcastReceiver to
 *            send results to. (For instance, if another plugin wanted to do
 *            its own handling.)
 * @param resultCode, the code sent back by the phone's Radio
 * @param seq, the message's sequence number
 * @param smsMsg, the message being processed
 */
private synchronized void handleSentMessage(Context context,
                                            BroadcastReceiver receiver, int resultCode, String smsMsg) {
  switch (resultCode) {
    case Activity.RESULT_OK:
      Log.i(TAG, "Received OK, msg:" + smsMsg);
      Toast.makeText(activity, "Message sent", Toast.LENGTH_SHORT).show();
      break;
    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
      Log.e(TAG, "Received generic failure, msg:" + smsMsg);
      Toast.makeText(activity, "Generic failure: message not sent", Toast.LENGTH_SHORT).show();
      break;
    case SmsManager.RESULT_ERROR_NO_SERVICE:
      Log.e(TAG, "Received no service error, msg:"  + smsMsg);
      Toast.makeText(activity, "No Sms service available. Message not sent.", Toast.LENGTH_SHORT).show();
      break;
    case SmsManager.RESULT_ERROR_NULL_PDU:
      Log.e(TAG, "Received null PDU error, msg:"  + smsMsg);
      Toast.makeText(activity, "Received null PDU error. Message not sent.", Toast.LENGTH_SHORT).show();
      break;
    case SmsManager.RESULT_ERROR_RADIO_OFF:
      Log.e(TAG, "Received radio off error, msg:" + smsMsg);
      Toast.makeText(activity, "Could not send SMS message: radio off.", Toast.LENGTH_LONG).show();
      break;
  }
}
 
Example #28
Source File: PluginBaseContextWrapper.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
@Override
public void sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver,
		Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
	PaLog.d(intent);
	intent = PluginIntentResolver.resolveReceiver(intent);
	super.sendOrderedBroadcast(intent, receiverPermission, resultReceiver,
			scheduler, initialCode, initialData, initialExtras);

}
 
Example #29
Source File: EncryptionCache.java    From oversec with GNU General Public License v3.0 5 votes vote down vote up
public EncryptionCache(Context ctx, CryptoHandlerFacade cryptoHandlerFacade) {
    mCtx = ctx;
    mCryptoHandlerFacade = cryptoHandlerFacade;


    BroadcastReceiver aIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                //clear the cache on screen off, in case keys are cleared in OKC on screen off
                // we need to immediately clear everything we have..
                clear(CLEAR_REASON.SCREEN_OFF, null);
            }
        }
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    ctx.registerReceiver(aIntentReceiver, filter);
}
 
Example #30
Source File: CaptureActivity.java    From barcodescanner-lib-aar with MIT License 5 votes vote down vote up
@Override
public void onCreate(Bundle icicle) {
  super.onCreate(icicle);

  Window window = getWindow();
  window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  setContentView(R.layout.capture);

  hasSurface = false;
  inactivityTimer = new InactivityTimer(this);
  beepManager = new BeepManager(this);
  ambientLightManager = new AmbientLightManager(this);

  PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

  stopReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      finish();
    }
  };
  LocalBroadcastManager.getInstance(this).registerReceiver(stopReceiver, new android.content.IntentFilter("barcode-scanner-stop"));
}