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: 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 #4
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 #5
Source File: InCallManagerModule.java    From react-native-incall-manager with ISC License 5 votes vote down vote up
/** Helper method for unregistration of an existing receiver. */
private void unregisterReceiver(final BroadcastReceiver receiver) {
    final ReactContext reactContext = this.getReactApplicationContext();
    if (reactContext != null) {
        try {
            reactContext.unregisterReceiver(receiver);
        } catch (final Exception e) {
            Log.d(TAG, "unregisterReceiver() failed");
        }
    } else {
        Log.d(TAG, "unregisterReceiver() reactContext is null");
    }
}
 
Example #6
Source File: SmsHandlerHook.java    From XposedSmsCode with GNU General Public License v3.0 5 votes vote down vote up
private void hookDispatchIntent21(ClassLoader classloader) {
    XLog.d("Hooking dispatchIntent() for Android v21+");
    XposedHelpers.findAndHookMethod(SMS_HANDLER_CLASS, classloader, "dispatchIntent",
            /*         intent */ Intent.class,
            /*     permission */ String.class,
            /*          appOp */ int.class,
            /* resultReceiver */ BroadcastReceiver.class,
            /*           user */ UserHandle.class,
            new DispatchIntentHook(3));
}
 
Example #7
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,
            null, resultReceiver, scheduler, initialCode, initialData, initialExtras);
}
 
Example #8
Source File: LocalBroadcastManager.java    From adt-leanback-support with Apache License 2.0 5 votes vote down vote up
/**
 * Unregister a previously registered BroadcastReceiver.  <em>All</em>
 * filters that have been registered for this BroadcastReceiver will be
 * removed.
 *
 * @param receiver The BroadcastReceiver to unregister.
 *
 * @see #registerReceiver
 */
public void unregisterReceiver(BroadcastReceiver receiver) {
    synchronized (mReceivers) {
        ArrayList<IntentFilter> filters = mReceivers.remove(receiver);
        if (filters == null) {
            return;
        }
        for (int i=0; i<filters.size(); i++) {
            IntentFilter filter = filters.get(i);
            for (int j=0; j<filter.countActions(); j++) {
                String action = filter.getAction(j);
                ArrayList<ReceiverRecord> receivers = mActions.get(action);
                if (receivers != null) {
                    for (int k=0; k<receivers.size(); k++) {
                        if (receivers.get(k).receiver == receiver) {
                            receivers.remove(k);
                            k--;
                        }
                    }
                    if (receivers.size() <= 0) {
                        mActions.remove(action);
                    }
                }
            }
        }
    }
}
 
Example #9
Source File: LocalBroadcastManager.java    From Dashchan with Apache License 2.0 5 votes vote down vote up
/**
 * Unregister a previously registered BroadcastReceiver. <em>All</em> filters that have been registered for this
 * BroadcastReceiver will be removed.
 *
 * @param receiver
 *            The BroadcastReceiver to unregister.
 *
 * @see #registerReceiver
 */
public void unregisterReceiver(BroadcastReceiver receiver) {
	synchronized (mReceivers) {
		ArrayList<IntentFilter> filters = mReceivers.remove(receiver);
		if (filters == null) {
			return;
		}
		for (int i = 0; i < filters.size(); i++) {
			IntentFilter filter = filters.get(i);
			for (int j = 0; j < filter.countActions(); j++) {
				String action = filter.getAction(j);
				ArrayList<ReceiverRecord> receivers = mActions.get(action);
				if (receivers != null) {
					for (int k = 0; k < receivers.size(); k++) {
						if (receivers.get(k).receiver == receiver) {
							receivers.remove(k);
							k--;
						}
					}
					if (receivers.size() <= 0) {
						mActions.remove(action);
					}
				}
			}
		}
	}
}
 
Example #10
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) {
    if (receiver == null) {
        // Allow retrieving current sticky broadcast; this is safe since we
        // aren't actually registering a receiver.
        return super.registerReceiver(null, filter, broadcastPermission, scheduler);
    } else {
        throw new ReceiverCallNotAllowedException(
                "BroadcastReceiver components are not allowed to register to receive intents");
    }
}
 
Example #11
Source File: GroupListActivity.java    From LQRWeChat with MIT License 5 votes vote down vote up
private void registerBR() {
    BroadcastManager.getInstance(this).register(AppConst.GROUP_LIST_UPDATE, new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mPresenter.loadGroups();
        }
    });
}
 
Example #12
Source File: FakeBatteryHook.java    From QNotified with GNU General Public License v3.0 5 votes vote down vote up
private static void doPostReceiveEvent(final BroadcastReceiver recv, final Context ctx, final Intent intent) {
    SyncUtils.post(new Runnable() {
        @Override
        public void run() {
            SyncUtils.setTlsFlag(_FLAG_MANUAL_CALL);
            try {
                recv.onReceive(ctx, intent);
            } catch (Throwable e) {
                log(e);
            }
            SyncUtils.clearTlsFlag(_FLAG_MANUAL_CALL);
        }
    });
}
 
Example #13
Source File: InstrumentationConnectionTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyCallingTerminateBeforeInitInitializeShouldNotExplode() {
  instrumentationConnection.terminate();
  instrumentationConnection.terminate();
  instrumentationConnection.terminate();

  // verify unregisterReceiver is never called
  verify(mockedContext, never()).unregisterReceiver(any(BroadcastReceiver.class));
}
 
Example #14
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 #15
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, int appOp, BroadcastReceiver resultReceiver,
        Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
    sendOrderedBroadcastAsUser(intent, user, receiverPermission, appOp,
            null, resultReceiver, scheduler, initialCode, initialData, initialExtras);
}
 
Example #16
Source File: BatteryListener.java    From jpHolo with MIT License 5 votes vote down vote up
/**
 * Executes the request.
 *
 * @param action        	The action to execute.
 * @param args          	JSONArry of arguments for the plugin.
 * @param callbackContext 	The callback context used when calling back into JavaScript.
 * @return              	True if the action was valid, false if not.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("start")) {
        if (this.batteryCallbackContext != null) {
            callbackContext.error( "Battery listener already running.");
            return true;
        }
        this.batteryCallbackContext = callbackContext;

        // We need to listen to power events to update battery status
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        if (this.receiver == null) {
            this.receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    updateBatteryInfo(intent);
                }
            };
            cordova.getActivity().registerReceiver(this.receiver, intentFilter);
        }

        // Don't return any result now, since status results will be sent when events come in from broadcast receiver
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    }

    else if (action.equals("stop")) {
        removeBatteryListener();
        this.sendUpdate(new JSONObject(), false); // release status callback in JS side
        this.batteryCallbackContext = null;
        callbackContext.success();
        return true;
    }

    return false;
}
 
Example #17
Source File: AndroidOperationTube.java    From java-unified-sdk with Apache License 2.0 5 votes vote down vote up
public boolean sendMessage(String clientId, String conversationId, int convType, final AVIMMessage message,
                           final AVIMMessageOption messageOption, final AVIMCommonJsonCallback callback) {
  BroadcastReceiver receiver = null;
  if (null != callback) {
    receiver = new AVIMBaseBroadcastReceiver(callback) {
      @Override
      public void execute(Map<String, Object> intentResult, Throwable error) {
        callback.internalDone(intentResult, AVIMException.wrapperAVException(error));
      }
    };
  }
  return this.sendClientCMDToPushService(clientId, conversationId, convType, null,
      message, messageOption, AVIMOperation.CONVERSATION_SEND_MESSAGE, receiver);
}
 
Example #18
Source File: AppUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 注销广播监听
 * @param receiver {@linkBroadcastReceiver}
 * @return {@code true} success, {@code false} fail
 */
public static boolean unregisterReceiver(final BroadcastReceiver receiver) {
    if (receiver == null) return false;
    try {
        DevUtils.getContext().unregisterReceiver(receiver);
        return true;
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "unregisterReceiver");
    }
    return false;
}
 
Example #19
Source File: DaedalusVpnService.java    From Daedalus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    if (Daedalus.getPrefs().getBoolean("settings_use_system_dns", false)) {
        registerReceiver(receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                updateUpstreamServers(context);
            }
        }, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
}
 
Example #20
Source File: PluginBaseContextWrapper.java    From Android-Plugin-Framework with MIT License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle user, BroadcastReceiver resultReceiver,
		Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
	LogUtil.v(intent);
	ArrayList<Intent> list = PluginIntentResolver.resolveReceiver(intent);
	for (Intent item:list) {
		super.sendStickyOrderedBroadcastAsUser(item, user, resultReceiver, scheduler, initialCode, initialData,
				initialExtras);
	}
}
 
Example #21
Source File: MainActivity.java    From effective_android_sample with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  mTextView = (TextView) findViewById(R.id.text_view);

  // アプリ起動時の機内モードの状態をTextViewに表示
  if (isAirplaneMode()) {
    mTextView.setText(R.string.airplane_mode_on);
  } else {
    mTextView.setText(R.string.airplane_mode_off);
  }

  // 通信状態の変更を取得するためのBroadcastReceiverを作成し、登録
  mReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
      // 通信状態の変更通知を受けて、TextViewの内容を更新
      if (isAirplaneMode()) {
        mTextView.setText(R.string.airplane_mode_on);
      } else {
        mTextView.setText(R.string.airplane_mode_off);
      }
    }
  };
  IntentFilter filter = new IntentFilter(
      ConnectivityManager.CONNECTIVITY_ACTION);
  registerReceiver(mReceiver, filter);
}
 
Example #22
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"));
}
 
Example #23
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 #24
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 #25
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 #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: 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 #28
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 #29
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 #30
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();
    }
}