Java Code Examples for android.content.Context#registerReceiver()

The following examples show how to use android.content.Context#registerReceiver() . 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: UsbStorageProvider.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
@Override
public boolean onCreate() {
    Context context = getContext();

    updateSettings();
    usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_USB_PERMISSION);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    context.registerReceiver(mUsbReceiver, filter);

    updateRoots();
    return true;
}
 
Example 2
Source File: MediaServiceHandler.java    From Aerlink-for-Android with MIT License 6 votes vote down vote up
public MediaServiceHandler(Context context, ServiceUtils serviceUtils) {
    this.mContext = context;
    this.mServiceUtils = serviceUtils;

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Constants.IA_HIDE_MEDIA);
    context.registerReceiver(mBroadcastReceiver, intentFilter);

    // Run on main thread
    final Handler handler = new Handler(mContext.getMainLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            prepareMediaSession();

            handler.removeCallbacksAndMessages(null);
        }
    });
}
 
Example 3
Source File: FloatLifecycle.java    From FloatWindow with Apache License 2.0 5 votes vote down vote up
FloatLifecycle(Context applicationContext, boolean showFlag, Class[] activities, LifecycleListener lifecycleListener) {
    this.showFlag = showFlag;
    this.activities = activities;
    num++;
    mLifecycleListener = lifecycleListener;
    mHandler = new Handler();
    ((Application) applicationContext).registerActivityLifecycleCallbacks(this);
    applicationContext.registerReceiver(this, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}
 
Example 4
Source File: EntropyMixer.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** Test only interface, not for public use */
public EntropyMixer(
        Context context,
        String entropyFile,
        String randomDevice,
        String hwRandomDevice) {
    if (randomDevice == null) { throw new NullPointerException("randomDevice"); }
    if (hwRandomDevice == null) { throw new NullPointerException("hwRandomDevice"); }
    if (entropyFile == null) { throw new NullPointerException("entropyFile"); }

    this.randomDevice = randomDevice;
    this.hwRandomDevice = hwRandomDevice;
    this.entropyFile = entropyFile;
    loadInitialEntropy();
    addDeviceSpecificEntropy();
    addHwRandomEntropy();
    writeEntropy();
    scheduleEntropyWriter();
    IntentFilter broadcastFilter = new IntentFilter(Intent.ACTION_SHUTDOWN);
    broadcastFilter.addAction(Intent.ACTION_POWER_CONNECTED);
    broadcastFilter.addAction(Intent.ACTION_REBOOT);
    context.registerReceiver(
            mBroadcastReceiver,
            broadcastFilter,
            null, // do not require broadcaster to hold any permissions
            mHandler // process received broadcasts on the I/O thread instead of the main thread
            );
}
 
Example 5
Source File: APKDownloader.java    From seny-devpkg with Apache License 2.0 5 votes vote down vote up
/**
 * 获取APKDownloader实例,同时注册DOWNLOAD_COMPLETE
 *
 * @return APKDownloader对象
 */
public static APKDownloader getInstance(Context context) {
    Assert.notNull(context);
    if (mInstance == null) {
        mInstance = new APKDownloader();
        mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction("android.intent.action.DOWNLOAD_COMPLETE");
        context.registerReceiver(receiver, intentfilter);
    }
    return mInstance;
}
 
Example 6
Source File: ConnectivityHelper.java    From AndroidCommons with Apache License 2.0 5 votes vote down vote up
/**
 * Be sure to remove receiver at appropriate time (i.e. in Activity.onPause()).
 */
@RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
public static void register(@NonNull Context context, @NonNull ConnectivityListener listener) {
    if (receiversMap.containsKey(listener)) {
        throw new RuntimeException("Connectivity listener " + listener
                + " is already registered");
    }

    final ConnectivityReceiver receiver = new ConnectivityReceiver(listener);
    receiversMap.put(listener, receiver);
    context.registerReceiver(receiver,
            new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    receiver.notify(isConnected(context));
}
 
Example 7
Source File: Battery.java    From batteryhub with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains the current battery voltage value.
 *
 * @param context Application context
 * @return Returns the battery voltage
 */
public static double getBatteryVoltage(final Context context) {
    Intent receiver = context.registerReceiver(
            null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED)
    );

    if (receiver == null) return 0;

    double voltage = receiver.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);

    return (voltage == 0) ? voltage : voltage / 1000;
}
 
Example 8
Source File: ServerPingWithAlarmManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Register a pending intent with the AlarmManager to be broadcasted every half hour and
 * register the alarm broadcast receiver to receive this intent. The receiver will check all
 * known questions if a ping is Necessary when invoked by the alarm intent.
 *
 * @param context an Android context.
 */
public static void onCreate(Context context) {
    sContext = context;
    context.registerReceiver(ALARM_BROADCAST_RECEIVER, new IntentFilter(PING_ALARM_ACTION));
    sAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    sPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(PING_ALARM_ACTION), 0);
    sAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_HALF_HOUR,
            AlarmManager.INTERVAL_HALF_HOUR, sPendingIntent);
}
 
Example 9
Source File: NetworkConnectivityListener.java    From Anecdote with Apache License 2.0 5 votes vote down vote up
/**
 * This method starts listening for network connectivity state changes.
 *
 * @param context app context
 */
public synchronized void startListening(Context context, ConnectivityListener connectivityListener) {
    if (mListener == null) {
        mContext = context;
        mMainHandler = new Handler(context.getMainLooper());
        mListener = connectivityListener;

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(mReceiver, filter);
    }
}
 
Example 10
Source File: ShareHelper.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
static void sendChooserIntent(boolean saveLastUsed, Activity activity,
                              Intent sharingIntent,
                              @Nullable TargetChosenCallback callback) {
    synchronized (LOCK) {
        if (sTargetChosenReceiveAction == null) {
            sTargetChosenReceiveAction = activity.getPackageName() + "/"
                    + TargetChosenReceiver.class.getName() + "_ACTION";
        }
        Context context = activity.getApplicationContext();
        if (sLastRegisteredReceiver != null) {
            context.unregisterReceiver(sLastRegisteredReceiver);
            // Must cancel the callback (to satisfy guarantee that exactly one method of
            // TargetChosenCallback is called).
            // TODO(mgiuca): This should be called immediately upon cancelling the chooser,
            // not just when the next share takes place (https://crbug.com/636274).
            sLastRegisteredReceiver.cancel();
        }
        sLastRegisteredReceiver = new TargetChosenReceiver(saveLastUsed, callback);
        context.registerReceiver(
                sLastRegisteredReceiver, new IntentFilter(sTargetChosenReceiveAction));
    }

    Intent intent = new Intent(sTargetChosenReceiveAction);
    intent.setPackage(activity.getPackageName());
    intent.putExtra(EXTRA_RECEIVER_TOKEN, sLastRegisteredReceiver.hashCode());
    final PendingIntent pendingIntent = PendingIntent.getBroadcast(activity, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
    Intent chooserIntent = Intent.createChooser(sharingIntent,
            activity.getString(R.string.share_link_chooser_title),
            pendingIntent.getIntentSender());
    if (sFakeIntentReceiverForTesting != null) {
        sFakeIntentReceiverForTesting.setIntentToSendBack(intent);
    }
    fireIntent(activity, chooserIntent);
}
 
Example 11
Source File: ViewUtils.java    From native-navigation with MIT License 5 votes vote down vote up
/**
 * https://developer.android.com/training/monitoring-device-state/battery-monitoring.html
 */
public static int getBatteryState(Context context) {
  IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
  Intent batteryStatus = context.registerReceiver(null, ifilter);
  if (batteryStatus == null) {
    return BatteryManager.BATTERY_STATUS_UNKNOWN;
  }
  return batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
}
 
Example 12
Source File: DefaultBandwidthMeter.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
public static synchronized ConnectivityActionReceiver getInstance(Context context) {
  if (staticInstance == null) {
    staticInstance = new ConnectivityActionReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    context.registerReceiver(staticInstance, filter);
  }
  return staticInstance;
}
 
Example 13
Source File: DefaultBandwidthMeter.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
public static synchronized ConnectivityActionReceiver getInstance(Context context) {
  if (staticInstance == null) {
    staticInstance = new ConnectivityActionReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    context.registerReceiver(staticInstance, filter);
  }
  return staticInstance;
}
 
Example 14
Source File: TracingControllerAndroid.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Register a BroadcastReceiver in the given context.
 */
public void registerReceiver(Context context) {
    context.registerReceiver(getBroadcastReceiver(), getIntentFilter());
}
 
Example 15
Source File: BlueMessageReceiver.java    From BluetoothSocket with Apache License 2.0 4 votes vote down vote up
public void register(Context context){
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BlueService.ACTION_MESSAGE_REVEIVER);
    context.registerReceiver(this,intentFilter);
}
 
Example 16
Source File: AndroidUtils.java    From Android-Next with Apache License 2.0 4 votes vote down vote up
public static Intent getBatteryStatus(Context context) {
    Context appContext = context.getApplicationContext();
    return appContext.registerReceiver(null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
 
Example 17
Source File: WeatherUtil.java    From apollo-DuerOS with Apache License 2.0 4 votes vote down vote up
public void init(Context context) {
    LogUtil.d(TAG, "init()");
    IntentFilter intentFilter = new IntentFilter(UPDATE_WEATHER_ACTION);
    context.registerReceiver(mReceiver, intentFilter);
    context.sendBroadcast(new Intent(REQUEST_UPDATE_WEATHER_ACTION));
}
 
Example 18
Source File: RxDownloader.java    From RxDownloader with MIT License 4 votes vote down vote up
public RxDownloader(@NonNull Context context) {
    this.context = context.getApplicationContext();
    DownloadStatusReceiver downloadStatusReceiver = new DownloadStatusReceiver();
    IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    context.registerReceiver(downloadStatusReceiver, intentFilter);
}
 
Example 19
Source File: TracingControllerAndroid.java    From android-chromium with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Register a BroadcastReceiver in the given context.
 */
public void registerReceiver(Context context) {
    context.registerReceiver(getBroadcastReceiver(), getIntentFilter());
}
 
Example 20
Source File: WifiUtil.java    From ShareBox with Apache License 2.0 4 votes vote down vote up
public static void getNearWifiList(final Context context, final WifiReceiver.IReceiveNewNetWorks listener)
{
    WifiManager manager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

    final WifiReceiver receiver=new WifiReceiver(manager);

    WifiReceiver.IReceiveNewNetWorks wListener=new WifiReceiver.IReceiveNewNetWorks() {

        WifiReceiver _receiver=receiver;

        @Override
        public void onReceive(ArrayList<ScanResult> list) {

            listener.onReceive(list);

            if(_receiver!=null)
            {
                try
                {
                    context.unregisterReceiver(_receiver);
                    _receiver=null;
                }catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

        }
    };

    receiver.setReceiveListener(wListener);

    manager.disconnect();

    if(!manager.isWifiEnabled())
      manager.setWifiEnabled(true);

    IntentFilter filter=new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);

    filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
    context.registerReceiver(receiver,filter);
}