コード例 #1
1
 public void register(Context context, Looper thread, UserHandle user, boolean externalStorage) {
   if (mRegisteredContext != null) {
     throw new IllegalStateException("Already registered");
   }
   mRegisteredContext = context;
   if (thread == null) {
     synchronized (sLock) {
       if (sBackgroundThread == null) {
         sBackgroundThread =
             new HandlerThread("PackageMonitor", android.os.Process.THREAD_PRIORITY_BACKGROUND);
         sBackgroundThread.start();
         sBackgroundHandler = new Handler(sBackgroundThread.getLooper());
       }
       mRegisteredHandler = sBackgroundHandler;
     }
   } else {
     mRegisteredHandler = new Handler(thread);
   }
   if (user != null) {
     context.registerReceiverAsUser(this, user, sPackageFilt, null, mRegisteredHandler);
     context.registerReceiverAsUser(this, user, sNonDataFilt, null, mRegisteredHandler);
     if (externalStorage) {
       context.registerReceiverAsUser(this, user, sExternalFilt, null, mRegisteredHandler);
     }
   } else {
     context.registerReceiver(this, sPackageFilt, null, mRegisteredHandler);
     context.registerReceiver(this, sNonDataFilt, null, mRegisteredHandler);
     if (externalStorage) {
       context.registerReceiver(this, sExternalFilt, null, mRegisteredHandler);
     }
   }
 }
コード例 #2
0
  /** Initializes IMS connection */
  public void initialize() {
    mCnxManager = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
    mNetwork = mRcsSettings.getNetworkAccess();
    mOperator = mRcsSettings.getNetworkOperator();

    /* Instantiates the IMS network interfaces */
    mNetworkInterfaces[0] = new MobileNetworkInterface(mImsModule, mRcsSettings);
    mNetworkInterfaces[1] = new WifiNetworkInterface(mImsModule, mRcsSettings);

    /* Set the mobile network interface by default */
    mCurrentNetworkInterface = getMobileNetworkInterface();

    loadUserProfile();

    if (mNetworkStateListener == null) {
      /* Register network state listener */
      mNetworkStateListener = new NetworkStateListener();
      mCtx.registerReceiver(
          mNetworkStateListener, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

    if (mBatteryLevelListener == null) {
      /* Register changes about battery: charging state, level, etc... */
      mBatteryLevelListener = new BatteryLevelListener();
      mCtx.registerReceiver(mBatteryLevelListener, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }
  }
コード例 #3
0
    @Override
    public void onStart() {
        final Context context = getContext();
        mTwilightManager = getLocalService(TwilightManager.class);
        final PowerManager powerManager =
                (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);

        context.registerReceiver(mDockModeReceiver,
                new IntentFilter(Intent.ACTION_DOCK_EVENT));
        context.registerReceiver(mBatteryReceiver,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

        mConfiguration.setToDefaults();

        mDefaultUiModeType = context.getResources().getInteger(
                com.android.internal.R.integer.config_defaultUiModeType);
        mCarModeKeepsScreenOn = (context.getResources().getInteger(
                com.android.internal.R.integer.config_carDockKeepsScreenOn) == 1);
        mDeskModeKeepsScreenOn = (context.getResources().getInteger(
                com.android.internal.R.integer.config_deskDockKeepsScreenOn) == 1);
        mTelevision = context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_TELEVISION) ||
            context.getPackageManager().hasSystemFeature(
                    PackageManager.FEATURE_LEANBACK);
        mWatch = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);

        mNightMode = Settings.Secure.getInt(context.getContentResolver(),
                Settings.Secure.UI_NIGHT_MODE, UiModeManager.MODE_NIGHT_AUTO);

        mTwilightManager.registerListener(mTwilightListener, mHandler);

        publishBinderService(Context.UI_MODE_SERVICE, mService);
    }
コード例 #4
0
    private void registerObserver() {
      // Here I register the ContentObserver and BroadcasetReceiver.
      // These can check the database's update and sdcard's state.
      // So, when there's no sdcard or database has no preview infos,
      // getCachedPreview() will be faster.
      synchronized (mRegisted) {
        if (!mRegisted) {
          mContentObserver = new MyContentObserver(null);
          mSdCardReceiver = new MyBroadcastReceiver();

          mCr.registerContentObserver(mUri, true, mContentObserver);

          IntentFilter filter1 = new IntentFilter(Intent.ACTION_MEDIA_EJECT);
          filter1.addDataScheme("file");
          mContext.registerReceiver(mSdCardReceiver, filter1);

          IntentFilter filter2 = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
          filter2.addDataScheme("file");
          mContext.registerReceiver(mSdCardReceiver, filter2);
          mRegisted = true;

          mMounted = isExternalStorageReady();
          if (LOG) Log.v(TAG, "registerObserver() regist observers! mMounted=" + mMounted);
        }
      }
      if (LOG) Log.v(TAG, "registerObserver() mRegisted=" + mRegisted + ", mMounted=" + mMounted);
    }
コード例 #5
0
  /*
     Bluetooth init function uses default bluetooth adapter.
     If there is no bluetooth devices in the system, it will show an error and
     exits program.

     If there is a bluetooth adapter, it checks if it is enabled. If not, it will
     call Bluetooth enable intent.

     Init function also sets broadcast call back for state changes. It is handled by
     BroadcastRx class which extends BroadcastReceiver.

  */
  public void init(Context mainActivity) {
    this.mainActivity = mainActivity;

    // TODO: if version is JELLY_BEAN_MR2 or higher use getSystemService(class)
    mBlueToothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBlueToothAdapter == null) {
      // Warn user and kill the app
      Toast.makeText(
              mainActivity.getApplicationContext(),
              "This device doesn't support Bluetooth!",
              Toast.LENGTH_LONG)
          .show();
      // TODO : throw an exception instead
      System.exit(0);
    }

    if (!mBlueToothAdapter.isEnabled()) {
      Toast.makeText(
              mainActivity.getApplicationContext(), "Please enable Bluetooth.", Toast.LENGTH_SHORT)
          .show();
      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      mainActivity.startActivity(enableBtIntent);
    }

    mReceiver = new BroadcastRx(mainActivity);
    // Register state change
    IntentFilter stateChangeIntentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    mainActivity.registerReceiver(mReceiver, stateChangeIntentFilter);
    stateChangeRegistered = true;

    // Register this class as the BroadcastReceiver callback handler.
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    mainActivity.registerReceiver(this, filter);
    broadcastRegistered = true;
  }
コード例 #6
0
 public void registerReceivers() {
   IntentFilter syncIntentFilter = new IntentFilter(ArticleSync.ACTION_SYNC);
   syncIntentFilter.addAction(ArticleSync.ACTION_NEW_SYNCED);
   context.registerReceiver(syncReceiver, syncIntentFilter);
   context.registerReceiver(updateReceiver, new IntentFilter(ArticleDao.ACTION_UPDATE));
   context.registerReceiver(
       tableClearReceiver, new IntentFilter(DatabaseHelper.ACTION_TABLES_CLEARED));
 }
コード例 #7
0
ファイル: SwitchLog.java プロジェクト: gcb/android-CPU-tuner
 public static void start(Context ctx) {
   if (instance == null) {
     instance = new SwitchLog(ctx);
   }
   instance.onReceive(ctx, getLogIntent(ctx.getString(R.string.log_msg_switchlog_start), false));
   ctx.registerReceiver(instance, new IntentFilter(Notifier.BROADCAST_PROFILE_CHANGED));
   ctx.registerReceiver(instance, new IntentFilter(ACTION_ADD_TO_LOG));
   ctx.registerReceiver(instance, new IntentFilter(ACTION_FLUSH_LOG));
 }
コード例 #8
0
ファイル: bn.java プロジェクト: BinSlashBash/xcrumby
 public void m1396o(Context context) {
   IntentFilter intentFilter = new IntentFilter();
   intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
   context.registerReceiver(this, intentFilter);
   intentFilter = new IntentFilter();
   intentFilter.addAction("com.google.analytics.RADIO_POWERED");
   intentFilter.addCategory(context.getPackageName());
   context.registerReceiver(this, intentFilter);
 }
  private void registerReceivers() {

    // EventBus.getDefault().post(new HeartRateEvent("Resistering receivers"));

    if (mContext != null) {
      mContext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
      final IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
      mContext.registerReceiver(mBlueToothReceiver, filter);
    }
  }
コード例 #10
0
 private void registerForPackageIntents() {
   IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
   filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
   filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
   filter.addDataScheme("package");
   mContext.registerReceiver(mPackageMonitor, filter);
   filter = new IntentFilter();
   filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
   filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
   mContext.registerReceiver(mPackageMonitor, filter);
 }
コード例 #11
0
  NotificationManagerService(
      Context context, StatusBarManagerService statusBar, LightsService lights) {
    super();
    mContext = context;
    mAm = ActivityManagerNative.getDefault();
    mSound = new NotificationPlayer(TAG);
    mSound.setUsesWakeLock(context);
    mToastQueue = new ArrayList<ToastRecord>();
    mHandler = new WorkerHandler();

    mStatusBar = statusBar;
    statusBar.setNotificationCallbacks(mNotificationCallbacks);

    mNotificationLight = lights.getLight(LightsService.LIGHT_ID_NOTIFICATIONS);
    mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);

    Resources resources = mContext.getResources();
    mDefaultNotificationColor =
        resources.getColor(com.android.internal.R.color.config_defaultNotificationColor);
    mDefaultNotificationLedOn =
        resources.getInteger(com.android.internal.R.integer.config_defaultNotificationLedOn);
    mDefaultNotificationLedOff =
        resources.getInteger(com.android.internal.R.integer.config_defaultNotificationLedOff);

    // Don't start allowing notifications until the setup wizard has run once.
    // After that, including subsequent boots, init with notifications turned on.
    // This works on the first boot because the setup wizard will toggle this
    // flag at least once and we'll go back to 0 after that.
    if (0
        == Settings.Secure.getInt(
            mContext.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0)) {
      mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
    }

    // register for various Intents
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    mContext.registerReceiver(mIntentReceiver, filter);
    IntentFilter pkgFilter = new IntentFilter();
    pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
    pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
    pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
    pkgFilter.addDataScheme("package");
    mContext.registerReceiver(mIntentReceiver, pkgFilter);
    IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
    mContext.registerReceiver(mIntentReceiver, sdFilter);

    SettingsObserver observer = new SettingsObserver(mHandler);
    observer.observe();
  }
コード例 #12
0
 public CustomLabelManager(Context context) {
   mContext = context;
   mPackageManager = context.getPackageManager();
   mLock = new Object();
   mShouldShutdownClient = false;
   mRunningTasks = 0;
   mClient = new LabelProviderClient(context, AUTHORITY);
   mContext.registerReceiver(mRefreshReceiver, REFRESH_INTENT_FILTER);
   mContext.registerReceiver(
       mLocaleChangedReceiver, new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
   refreshCache();
 }
コード例 #13
0
  public BleManager(final Context context) {
    mContext = context;
    mHandler = new Handler();
    mUserDisconnected = false;

    // Register bonding broadcast receiver
    context.registerReceiver(
        mBondingBroadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
    context.registerReceiver(
        mPairingRequestBroadcastReceiver,
        new IntentFilter(
            "android.bluetooth.device.action.PAIRING_REQUEST" /*BluetoothDevice.ACTION_PAIRING_REQUEST*/));
  }
コード例 #14
0
ファイル: SystemHelper.java プロジェクト: bomzaiya/idang
 /**
  * Register for being notified of changes to the battery level. Note: After registering, the
  * callback method will be called immediately with the current battery level
  *
  * @param jsCallbackMethodName name of the JavaScript method to call on every change to the
  *     battery level. This method needs to have two parameter, the first receives the battery
  *     level as an integer value from 0 to 5, the second true when the battery is charging, false
  *     when not charging
  */
 public static BroadcastReceiver registerBatteryLevelListener(
     final Context context, final OnBatteryListener onBatteryListener) {
   BroadcastReceiver batteryChangedReceiver =
       new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
           onBatteryLevelIntent(intent, onBatteryListener);
         }
       };
   IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
   context.registerReceiver(batteryChangedReceiver, filter);
   onBatteryLevelIntent(context.registerReceiver(null, filter), onBatteryListener);
   return batteryChangedReceiver;
 }
コード例 #15
0
ファイル: ToolPhone.java プロジェクト: ykbjson/SMTCompat
  /**
   * 直接调用短信API发送信息(设置监听发送和接收状态)
   *
   * @param strPhone 手机号码
   * @param strMsgContext 短信内容
   */
  public static void sendMessage(
      final Context mContext, final String strPhone, final String strMsgContext) {

    // 处理返回的发送状态
    String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    Intent sentIntent = new Intent(SENT_SMS_ACTION);
    PendingIntent sendIntent = PendingIntent.getBroadcast(mContext, 0, sentIntent, 0);
    // register the Broadcast Receivers
    mContext.registerReceiver(
        new BroadcastReceiver() {
          @Override
          public void onReceive(Context _context, Intent _intent) {
            switch (getResultCode()) {
              case Activity.RESULT_OK:
                Toast.makeText(mContext, "短信发送成功", Toast.LENGTH_SHORT).show();
                break;
              case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                break;
              case SmsManager.RESULT_ERROR_RADIO_OFF:
                break;
              case SmsManager.RESULT_ERROR_NULL_PDU:
                break;
            }
          }
        },
        new IntentFilter(SENT_SMS_ACTION));

    // 处理返回的接收状态
    String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
    // createSpannableString the deilverIntent parameter
    Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
    PendingIntent backIntent = PendingIntent.getBroadcast(mContext, 0, deliverIntent, 0);
    mContext.registerReceiver(
        new BroadcastReceiver() {
          @Override
          public void onReceive(Context _context, Intent _intent) {
            Toast.makeText(mContext, strPhone + "已经成功接收", Toast.LENGTH_SHORT).show();
          }
        },
        new IntentFilter(DELIVERED_SMS_ACTION));

    // 拆分短信内容(手机短信长度限制)
    SmsManager smsManager = SmsManager.getDefault();
    ArrayList<String> msgList = smsManager.divideMessage(strMsgContext);
    for (String text : msgList) {
      smsManager.sendTextMessage(strPhone, null, text, sendIntent, backIntent);
    }
  }
コード例 #16
0
  /**
   * Searches for the device and opens it if successful
   *
   * @return true, if connection was successful
   */
  public boolean FindDevice() {
    _usbManager = (UsbManager) _context.getSystemService(Context.USB_SERVICE);

    HashMap<String, UsbDevice> deviceList = _usbManager.getDeviceList();

    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    _usbDevice = null;

    // Iterate all the available devices and find ours.
    while (deviceIterator.hasNext()) {
      UsbDevice device = deviceIterator.next();
      if (device.getProductId() == _productId && device.getVendorId() == _vendorId) {
        _usbDevice = device;
        _deviceName = _usbDevice.getDeviceName();
      }
    }

    if (_usbDevice == null) {
      Log("Cannot find the device. Did you forgot to plug it?");
      Log(String.format("\t I search for VendorId: %s and ProductId: %s", _vendorId, _productId));
      _connectionHandler.onDeviceNotFound();
      return false;
    }

    // Create and intent and request a permission.
    PendingIntent mPermissionIntent =
        PendingIntent.getBroadcast(_context, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    _context.registerReceiver(mUsbReceiver, filter);

    _usbManager.requestPermission(_usbDevice, mPermissionIntent);
    Log("Found the device and requested permission.");
    return true;
  }
コード例 #17
0
 private void createBrodcastReveiver() {
   // TODO Auto-generated method stub
   IntentFilter filter = new IntentFilter();
   SKY_TV_STATE_CHANGED_BROADCAST[] val = SKY_TV_STATE_CHANGED_BROADCAST.values();
   for (int i = 0; i < val.length; i++) filter.addAction(val[i].toString());
   mContext.registerReceiver(reveiver, filter);
 }
コード例 #18
0
ファイル: Core.java プロジェクト: FDUChat/FDUChat-Android
 private void registerMessageReceiver(Context context) {
   infoReceiver = new InfoReceiver();
   IntentFilter filter = new IntentFilter();
   filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
   filter.addAction(Constant.MESSAGE_RECEIVED);
   context.registerReceiver(infoReceiver, filter);
 }
 private void initialize() {
   // register our receiver on our thread rather than the main thread
   IntentFilter intentFilter = new IntentFilter();
   intentFilter.addAction(ALARM_WAKEUP);
   intentFilter.addAction(ALARM_TIMEOUT);
   mContext.registerReceiver(mBroadcastReciever, intentFilter);
 }
コード例 #20
0
  private void initReceiverDownloadComplete() {
    //        filter for download - on completion
    IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

    receiverDownloadComplete =
        new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
            long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (myDownloadReference == reference) {
              //                    do something with the download file
              DownloadManager.Query query = new DownloadManager.Query();
              query.setFilterById(reference);
              Cursor cursor = downloadManager.query(query);

              cursor.moveToFirst();
              //                        get the status of the download
              int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
              int status = cursor.getInt(columnIndex);
              int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
              int reason = cursor.getInt(columnReason);

              getDownloadStatus(context, status, reason);
              cursor.close();
            }
          }
        };

    context.registerReceiver(receiverDownloadComplete, intentFilter);
  }
コード例 #21
0
  public int onStartCommand(Intent intent, int flags, int startId) {

    if (DBG) log("Bluetooth Dun Service is started");

    if (!mHasInitiated) {
      if (!initNative()) {
        Log.e(TAG, "Could not init BluetoothDunService");
        notifyProfileState(BluetoothProfileManager.STATE_ABNORMAL);
        return START_STICKY;
      }

      IntentFilter intentFilter = new IntentFilter();
      intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
      intentFilter.addAction(BluetoothDunService.ACCESS_RESPONSE_ACTION);
      intentFilter.addAction(BluetoothDunService.RESEND_NOTIFICATION_ACTION);
      intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
      intentFilter.addAction(BluetoothTethering.BLUETOOTH_INTERFACE_ADDED);
      mContext.registerReceiver(mReceiver, intentFilter);

      mBTtethering = BluetoothTethering.getBluetoothTetheringInstance();
      mBTtethering.registerBTTether(this);

      dunEnableNative();
      // broadcast enabling to profilemanager
      notifyProfileState(BluetoothProfileManager.STATE_ENABLING);

      mHasInitiated = true;
    } else {
      if (DBG) log("Already started, just return!");
      return START_STICKY;
    }

    return START_STICKY;
  }
コード例 #22
0
  public KeyHandler(Context context) {
    mContext = context;
    mHandler = new Handler();

    mSettingsIntent = new Intent(Intent.ACTION_MAIN, null);
    mSettingsIntent.setAction(Settings.ACTION_SETTINGS);
    mSettingsIntent.addFlags(
        Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

    mAutomaticAvailable =
        context
            .getResources()
            .getBoolean(com.android.internal.R.bool.config_automatic_brightness_available);

    try {
      if (Settings.Secure.getInt(mContext.getContentResolver(), SETTING_TOUCHPAD_STATUS) == 0) {
        mTouchpadEnabled = false;
        nativeToggleTouchpad(false);
      }
    } catch (SettingNotFoundException e) {
    }

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_DOCK_EVENT);
    context.registerReceiver(mDockReceiver, filter);
  }
コード例 #23
0
  public View getContextCard(Context context) {

    sContext = context;

    // Tell Android that you'll monitor the stream statuses
    IntentFilter filter = new IntentFilter();
    filter.addAction(Stream_UI.ACTION_AWARE_STREAM_OPEN);
    filter.addAction(Stream_UI.ACTION_AWARE_STREAM_CLOSED);
    context.registerReceiver(streamObs, filter);

    // Load card information to memory
    LayoutInflater sInflater =
        (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    card = sInflater.inflate(R.layout.layout, null);

    // Initialize UI elements from the card
    still = (TextView) card.findViewById(R.id.time_still);
    walking = (TextView) card.findViewById(R.id.time_walking);
    biking = (TextView) card.findViewById(R.id.time_biking);
    running = (TextView) card.findViewById(R.id.time_running);
    driving = (TextView) card.findViewById(R.id.time_vehicle);

    // Begin refresh cycle
    uiRefresher.post(uiChanger);

    // Return the card to AWARE/apps
    return card;
  }
コード例 #24
0
 @Override
 public void onCreate(@Nullable Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   context = getActivity();
   myReceiver = new MyReceiver();
   context.registerReceiver(myReceiver, new IntentFilter(BROADCAST_ASTION));
 }
コード例 #25
0
  /**
   * Sets up a broadcastReceiver to listen for wifi hardware getting disabled
   *
   * @param disabled Callback listener to be fired if the wifi hardware is disabled
   */
  private synchronized void investWifiInterest(final HardwareCallback callback, final int index) {
    IntentFilter wifiInterestIntent = new IntentFilter();
    wifiInterestIntent.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);

    if (wifiInterestReceiver != null) {
      mContext.unregisterReceiver(wifiInterestReceiver);
    }

    wifiInterestReceiver =
        new BroadcastReceiver() {

          public void onReceive(Context context, Intent intent) {

            switch (mWifiManager.getWifiState()) {
              case WifiManager.WIFI_STATE_DISABLED:
              case WifiManager.WIFI_STATE_DISABLING:
              case WifiManager.WIFI_STATE_UNKNOWN:
                mContext.unregisterReceiver(wifiInterestReceiver);
                callback.hardwareDisabled(index, HardwareCallback.REASON_WIFI_USER);
                break;
            }
          }
        };

    mContext.registerReceiver(wifiInterestReceiver, wifiInterestIntent);
  }
コード例 #26
0
 public NetworkToggle(Context context) {
   super(context);
   setLabel(R.string.toggle_data);
   mDataEnabled = isMobileDataEnabled();
   context.registerReceiver(getBroadcastReceiver(), getIntentFilter());
   updateState();
 }
コード例 #27
0
ファイル: GCMRegistrar.java プロジェクト: rnavagamuwa/wso2GCM
 /** Lazy initializes the {@link GCMBroadcastReceiver} instance. */
 static synchronized void setRetryBroadcastReceiver(Context context) {
   if (sRetryReceiver == null) {
     if (sRetryReceiverClassName == null) {
       // should never happen
       Log.e(TAG, "internal error: retry receiver class not set yet");
       sRetryReceiver = new GCMBroadcastReceiver();
     } else {
       Class<?> clazz;
       try {
         clazz = Class.forName(sRetryReceiverClassName);
         sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance();
       } catch (Exception e) {
         Log.e(
             TAG,
             "Could not create instance of "
                 + sRetryReceiverClassName
                 + ". Using "
                 + GCMBroadcastReceiver.class.getName()
                 + " directly.");
         sRetryReceiver = new GCMBroadcastReceiver();
       }
     }
     String category = context.getPackageName();
     IntentFilter filter = new IntentFilter(GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY);
     filter.addCategory(category);
     // must use a permission that is defined on manifest for sure
     String permission = category + ".permission.C2D_MESSAGE";
     Log.v(TAG, "Registering retry receiver");
     sRetryReceiverContext = context;
     sRetryReceiverContext.registerReceiver(sRetryReceiver, filter, permission, null);
   }
 }
コード例 #28
0
 // ×¢²á¼àÌý
 private void registerScreenBroadcastReceiver() {
   // TODO Auto-generated method stub
   IntentFilter filter = new IntentFilter();
   filter.addAction(Intent.ACTION_SCREEN_ON);
   filter.addAction(Intent.ACTION_SCREEN_OFF);
   mContext.registerReceiver(mScrennBroadcastReceiver, filter);
 }
コード例 #29
0
        /* It is used for Settings application. Not update the value util BT is on.
         */
        public void setBluetoothTethering(boolean value) {
          if (!value) {
            if (mDunState == BluetoothDun.STATE_CONNECTING) {
              dunConnectRspNative(mDunConnPath, false);
            } else if (mDunState == BluetoothDun.STATE_CONNECTED) {
              dunDisconnectNative();
            }
          }

          if (mAdapter.getState() != BluetoothAdapter.STATE_ON && value) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
            mTetheringReceiver =
                new BroadcastReceiver() {
                  @Override
                  public void onReceive(Context context, Intent intent) {
                    if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF)
                        == BluetoothAdapter.STATE_ON) {
                      mTetheringOn = true;
                      mContext.unregisterReceiver(mTetheringReceiver);
                    }
                  }
                };
            mContext.registerReceiver(mTetheringReceiver, filter);
          } else {
            mTetheringOn = value;
          }
        }
コード例 #30
0
  public BatteryService(Context context, LightsService lights) {
    mContext = context;
    mHandler = new Handler(true /*async*/);
    mLed = new Led(context, lights);
    mBatteryStats = BatteryStatsService.getService();

    mCriticalBatteryLevel =
        mContext
            .getResources()
            .getInteger(com.android.internal.R.integer.config_criticalBatteryWarningLevel);
    mLowBatteryWarningLevel =
        mContext
            .getResources()
            .getInteger(com.android.internal.R.integer.config_lowBatteryWarningLevel);
    mLowBatteryCloseWarningLevel =
        mContext
            .getResources()
            .getInteger(com.android.internal.R.integer.config_lowBatteryCloseWarningLevel);
    mShutdownBatteryTemperature =
        mContext
            .getResources()
            .getInteger(com.android.internal.R.integer.config_shutdownBatteryTemperature);

    // watch for invalid charger messages if the invalid_charger switch exists
    if (new File("/sys/devices/virtual/switch/invalid_charger/state").exists()) {
      mInvalidChargerObserver.startObserving("DEVPATH=/devices/virtual/switch/invalid_charger");
    }

    mBatteryPropertiesListener = new BatteryListener();

    IBinder b = ServiceManager.getService("batterypropreg");
    mBatteryPropertiesRegistrar = IBatteryPropertiesRegistrar.Stub.asInterface(b);

    try {
      mBatteryPropertiesRegistrar.registerListener(mBatteryPropertiesListener);
    } catch (RemoteException e) {
      // Should never happen.
    }
    if (FeatureOption.MTK_IPO_SUPPORT == true) {
      IntentFilter filter = new IntentFilter();
      filter.addAction(IPO_POWER_ON);
      filter.addAction(IPO_POWER_OFF);
      mContext.registerReceiver(
          new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
              if (IPO_POWER_ON.equals(intent.getAction())) {
                mIPOShutdown = false;
                mIPOBoot = true;
                // Let BatteryService to handle low battery warning.
                mLastBatteryLevel = mLowBatteryWarningLevel + 1;
                update(mBatteryProps);
              } else if (IPO_POWER_OFF.equals(intent.getAction())) {
                mIPOShutdown = true;
              }
            }
          },
          filter);
    }
  }