Example usage for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED

List of usage examples for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED

Introduction

In this page you can find the example usage for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED.

Prototype

String ACTION_STATE_CHANGED

To view the source code for android.bluetooth BluetoothAdapter ACTION_STATE_CHANGED.

Click Source Link

Document

Broadcast Action: The state of the local Bluetooth adapter has been changed.

Usage

From source file:is.hello.buruberi.bluetooth.stacks.android.NativeGattPeripheral.java

private void startObservingBluetoothState() {
    this.bluetoothStateReceiver = new BroadcastReceiver() {
        @Override/*from ww  w . j av a 2  s  .  c  o  m*/
        public void onReceive(Context context, Intent intent) {
            logger.info(LOG_TAG, "User disabled bluetooth radio, abandoning connection");

            if (!stack.getAdapter().isEnabled() && gatt != null) {
                gatt.disconnect();
            }
        }
    };
    final IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    stack.applicationContext.registerReceiver(bluetoothStateReceiver, filter);
}

From source file:br.liveo.ndrawer.ui.activity.MainActivity.java

License:asdf

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override//from w w w  .java2 s  . co  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    MovementProfile.status = 0;

    startingPosition = 0;

    registBroadcastReceiver();
    getInstanceIdToken();

    mDeviceAdapter = new DeviceListAdapter(this, R.layout.device_item);

    mHandler = new Handler();
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, "BLE Not Supported", Toast.LENGTH_SHORT).show();
        finish();
    }

    mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = mBluetoothManager.getAdapter();
    timer = new Timer();

    mBluetoothDeviceList = new ArrayList<BluetoothDevice>();

    // Register the BroadcastReceiver
    mFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    mFilter.addAction(ACTION_GATT_CONNECTED);
    mFilter.addAction(ACTION_GATT_DISCONNECTED);
    mFilter.addAction(ACTION_GATT_SERVICES_DISCOVERED);
    mFilter.addAction(ACTION_DATA_NOTIFY);
    mFilter.addAction(ACTION_DATA_WRITE);
    mFilter.addAction(ACTION_DATA_READ);

    if (isRegister == 0) {
        registerReceiver(mReceiver, mFilter);
    }

    mainActivity = this;

    Thread queueThread = new Thread() {
        @Override
        public void run() {
            while (true) {
                executeQueue();
                try {
                    Thread.sleep(0, 100000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    queueThread.start();
}

From source file:is.hello.buruberi.bluetooth.stacks.android.NativeBluetoothStack.java

@Override
@RequiresPermission(allOf = { Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, })
public Observable<Void> turnOn() {
    if (adapter == null) {
        return Observable.error(new ChangePowerStateException());
    }//from www .j  a va 2 s .  c  o m

    final ReplaySubject<Void> turnOnMirror = ReplaySubject.createWithSize(1);
    final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE,
                    BluetoothAdapter.ERROR);
            final int newState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            if (oldState == BluetoothAdapter.STATE_OFF && newState == BluetoothAdapter.STATE_TURNING_ON) {
                logger.info(LOG_TAG, "Bluetooth turning on");
            } else if (oldState == BluetoothAdapter.STATE_TURNING_ON && newState == BluetoothAdapter.STATE_ON) {
                logger.info(LOG_TAG, "Bluetooth turned on");

                applicationContext.unregisterReceiver(this);

                turnOnMirror.onNext(null);
                turnOnMirror.onCompleted();
            } else {
                logger.info(LOG_TAG, "Bluetooth failed to turn on");

                applicationContext.unregisterReceiver(this);

                turnOnMirror.onError(new ChangePowerStateException());
            }
        }
    };
    applicationContext.registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
    if (!adapter.enable()) {
        applicationContext.unregisterReceiver(receiver);
        return Observable.error(new ChangePowerStateException());
    }

    return turnOnMirror;
}

From source file:org.bart452.runningshoesensor.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    requestPermission();//from  w  w  w  .  j  av a 2  s. c  om
    context = getApplicationContext();

    mHeaderImageView = (ImageView) findViewById(R.id.appBarIv);
    Picasso.with(context).load(R.drawable.sunset_road_landscape).into(mHeaderImageView);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.toolBar);
    setSupportActionBar(mToolbar);
    mCollapsingTb = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar);
    mCollapsingTb.setTitle("Shoe sensor");
    mCollapsingTb.setExpandedTitleGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);

    // Bluetooth
    final BluetoothManager mBleMan = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBleAdapter = mBleMan.getAdapter();
    mBleScanner = mBleAdapter.getBluetoothLeScanner();
    mCharList = new ArrayList<>();
    mBleSem = new Semaphore(1);
    mBleThread = new BleThread(mBleSem);
    mBleThread.start();

    mBleReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
                if (mBleAdapter.getState() == BluetoothAdapter.STATE_ON) {
                    Log.d(LOG_TAG, "BT ON");
                    mScanFab.setEnabled(true);
                    if (mSnackBar != null) {
                        if (mSnackBar.isShown())
                            mSnackBar.dismiss();
                    }
                } else {
                    mScanFab.setEnabled(false);
                    bleEnable();
                }
            }
        }
    };

    // Text
    mDevNameTv = (TextView) findViewById(R.id.devNameTv);
    mDevNameTv.setText(getString(R.string.device_name) + " No device found");
    mRssiTv = (TextView) findViewById(R.id.rssiTv);
    mAddrTv = (TextView) findViewById(R.id.devAddrTv);

    // Buttons and switches
    mScanFab = (FloatingActionButton) findViewById(R.id.scanFab);
    mScanFab.setOnClickListener(this);
    mConnSwitch = (Switch) findViewById(R.id.connSwitch);
    mConnSwitch.setOnClickListener(this);

    //Graph
    mDataGraph = (GraphView) findViewById(R.id.dataGraph);
    mDataXSeries = new LineGraphSeries<>();
    mDataYSeries = new LineGraphSeries<>();
    mDataYSeries.setBackgroundColor(Color.RED);
    mDataGraph.addSeries(mDataXSeries);
    mDataGraph.addSeries(mDataYSeries);
    mDataGraph.getViewport().setXAxisBoundsManual(true);
    mDataGraph.getViewport().setMinX(0);
    mDataGraph.getViewport().setMaxX(20);

    // Animation
    mRotateAnim = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f);
    mRotateAnim.setDuration(SCAN_PERIOD);
    mRotateAnim.setInterpolator(new LinearInterpolator());
    bleEnable();
}

From source file:ac.robinson.bettertogether.hotspot.HotspotManagerService.java

@SuppressFBWarnings("REC_CATCH_EXCEPTION")
@Nullable//from w w w.  j  av  a2  s .c om
@Override
public IBinder onBind(Intent intent) {
    if (!mIsBound) {
        //TODO: check mBluetoothAdapter not null and/or check bluetooth is available - BluetoothUtils.isBluetoothAvailable()
        mBluetoothAdapter = BluetoothUtils.getBluetoothAdapter(HotspotManagerService.this);
        mOriginalBluetoothStatus = mBluetoothAdapter.isEnabled();
        mOriginalBluetoothName = mBluetoothAdapter.getName();

        //TODO: check mWifiManager not null and/or check bluetooth is available - WifiUtils.isWifiAvailable()
        // note we need the WifiManager for connecting to other hotspots regardless of whether we can create our own
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        // try to get the original state to restore later
        int wifiState = mWifiManager.getWifiState();
        switch (wifiState) {
        case WifiManager.WIFI_STATE_ENABLED:
        case WifiManager.WIFI_STATE_ENABLING:
            mOriginalWifiStatus = true;
            break;
        case WifiManager.WIFI_STATE_DISABLED:
        case WifiManager.WIFI_STATE_DISABLING:
        case WifiManager.WIFI_STATE_UNKNOWN:
            mOriginalWifiStatus = false;
            break;
        default:
            break;
        }

        // try to save the existing hotspot state
        if (CREATE_WIFI_HOTSPOT_SUPPORTED) {
            try {
                // TODO: is it possible to save/restore the original password? (WifiConfiguration doesn't hold the password)
                WifiConfiguration wifiConfiguration = WifiUtils.getWifiHotspotConfiguration(mWifiManager);
                mOriginalHotspotConfiguration = new ConnectionOptions();
                mOriginalHotspotConfiguration.mName = wifiConfiguration.SSID;
            } catch (Exception ignored) {
                // note - need to catch Exception rather than ReflectiveOperationException due to our API level (requires 19)
            }
        }

        // set up background thread for message sending - see: https://medium.com/@ali.muzaffar/dc8bf1540341
        mMessageThread = new HandlerThread("BTMessageThread");
        mMessageThread.start();
        mMessageThreadHandler = new Handler(mMessageThread.getLooper());

        // set up listeners for network/bluetooth state changes
        IntentFilter intentFilter = new IntentFilter();
        if (CREATE_WIFI_HOTSPOT_SUPPORTED) {
            intentFilter.addAction(HOTSPOT_STATE_FILTER); // Wifi hotspot states
        }
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); // Wifi on/off
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); // network connection/disconnection
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); // Bluetooth on/off
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND); // Bluetooth device found
        registerReceiver(mGlobalBroadcastReceiver, intentFilter);

        // listen for messages from our PluginMessageReceiver
        IntentFilter localIntentFilter = new IntentFilter();
        localIntentFilter.addAction(PluginIntent.ACTION_MESSAGE_RECEIVED);
        localIntentFilter.addAction(PluginIntent.ACTION_STOP_PLUGIN);
        LocalBroadcastManager.getInstance(HotspotManagerService.this).registerReceiver(mLocalBroadcastReceiver,
                localIntentFilter);

        // listen for EventBus events (from wifi/bluetooth servers)
        if (!EventBus.getDefault().isRegistered(HotspotManagerService.this)) {
            EventBus.getDefault().register(HotspotManagerService.this);
        }

        mIsBound = true;
    }

    return mMessenger.getBinder();
}

From source file:is.hello.buruberi.bluetooth.stacks.android.NativeBluetoothStack.java

@Override
@RequiresPermission(allOf = { Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, })
public Observable<Void> turnOff() {
    if (adapter == null) {
        return Observable.error(new ChangePowerStateException());
    }//  w w  w  .  j a  v  a  2  s. c  o  m

    final ReplaySubject<Void> turnOnMirror = ReplaySubject.createWithSize(1);
    final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE,
                    BluetoothAdapter.ERROR);
            final int newState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            if (oldState == BluetoothAdapter.STATE_ON && newState == BluetoothAdapter.STATE_TURNING_OFF) {
                logger.info(LOG_TAG, "Bluetooth turning off");
            } else if (oldState == BluetoothAdapter.STATE_TURNING_OFF
                    && newState == BluetoothAdapter.STATE_OFF) {
                logger.info(LOG_TAG, "Bluetooth turned off");

                applicationContext.unregisterReceiver(this);

                turnOnMirror.onNext(null);
                turnOnMirror.onCompleted();
            } else {
                logger.info(LOG_TAG, "Bluetooth failed to turn off");

                applicationContext.unregisterReceiver(this);

                turnOnMirror.onError(new ChangePowerStateException());
            }
        }
    };
    applicationContext.registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
    if (!adapter.disable()) {
        applicationContext.unregisterReceiver(receiver);
        return Observable.error(new ChangePowerStateException());
    }

    return turnOnMirror;
}

From source file:com.commontime.plugin.LocationManager.java

private void initBluetoothListener() {

    //check access
    if (!hasBlueToothPermission()) {
        debugWarn("Cannot listen to Bluetooth service when BLUETOOTH permission is not added");
        return;/* ww  w. j  a va 2 s .co m*/
    }

    //check device support
    try {
        iBeaconManager.checkAvailability();
    } catch (Exception e) {
        //if device does not support iBeacons an error is thrown
        debugWarn("Cannot listen to Bluetooth service: " + e.getMessage());
        return;
    }

    if (broadcastReceiver != null) {
        debugWarn("Already listening to Bluetooth service, not adding again");
        return;
    }

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

            // Only listen for Bluetooth server changes
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {

                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE,
                        BluetoothAdapter.ERROR);

                debugLog("Bluetooth Service state changed from " + getStateDescription(oldState) + " to "
                        + getStateDescription(state));

                switch (state) {
                case BluetoothAdapter.ERROR:
                    beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusNotDetermined");
                    break;
                case BluetoothAdapter.STATE_OFF:
                case BluetoothAdapter.STATE_TURNING_OFF:
                    if (oldState == BluetoothAdapter.STATE_ON)
                        beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusDenied");
                    break;
                case BluetoothAdapter.STATE_ON:
                    beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusAuthorized");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    break;
                }
            }
        }

        private String getStateDescription(int state) {
            switch (state) {
            case BluetoothAdapter.ERROR:
                return "ERROR";
            case BluetoothAdapter.STATE_OFF:
                return "STATE_OFF";
            case BluetoothAdapter.STATE_TURNING_OFF:
                return "STATE_TURNING_OFF";
            case BluetoothAdapter.STATE_ON:
                return "STATE_ON";
            case BluetoothAdapter.STATE_TURNING_ON:
                return "STATE_TURNING_ON";
            }
            return "ERROR" + state;
        }
    };

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    cordova.getActivity().registerReceiver(broadcastReceiver, filter);
}

From source file:com.t2.compassionMeditation.DeviceManagerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mInstance = this;
    sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    //this.sendBroadcast(new Intent(BioFeedbackService.ACTION_SERVICE_START));

    this.setContentView(R.layout.device_manager_activity_layout);

    this.findViewById(R.id.bluetoothSettingsButton).setOnClickListener(this);

    Resources resources = this.getResources();
    AssetManager assetManager = resources.getAssets();
    try {/* ww w  .  j  a v a  2 s  . c o  m*/
        mSpineManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources);
    } catch (InstantiationException e) {
        Log.e(TAG, this.getClass().getSimpleName() + " Exception creating SPINE manager: " + e.toString());
        e.printStackTrace();
    }
    // ... then we need to register a SPINEListener implementation to the SPINE manager instance
    // to receive sensor node data from the Spine server
    // (I register myself since I'm a SPINEListener implementation!)
    mSpineManager.addListener(this);

    // Create a broadcast receiver. Note that this is used ONLY for command messages from the service
    // All data from the service goes through the mail SPINE mechanism (received(Data data)).
    // See public void received(Data data)
    this.mCommandReceiver = new SpineReceiver(this);
    // Set up filter intents so we can receive broadcasts
    IntentFilter filter = new IntentFilter();
    filter.addAction("com.t2.biofeedback.service.status.BROADCAST");
    filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    filter.addAction(BioFeedbackService.ACTION_STATUS_BROADCAST);

    this.registerReceiver(this.mCommandReceiver, filter);

    // Tell the bluetooth service to send us a list of bluetooth devices and system status
    // Response comes in public void onStatusReceived(BioFeedbackStatus bfs) STATUS_PAIRED_DEVICES      
    mSpineManager.pollBluetoothDevices();

    //      this.deviceManager = DeviceManager.getInstance(this.getBaseContext(), null);
    this.deviceList = (ListView) this.findViewById(R.id.list);

    this.deviceListAdapter = new ManagerItemAdapter(this, R.layout.manager_item);
    this.deviceList.setAdapter(this.deviceListAdapter);

    this.bluetoothDisabledDialog = new AlertDialog.Builder(this).setMessage("Bluetooth is not enabled.")
            .setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    finish();
                }
            }).setPositiveButton("Setup Bluetooth", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startBluetoothSettings();
                }
            }).create();

    try {
        PackageManager packageManager = this.getPackageManager();
        PackageInfo info = packageManager.getPackageInfo(this.getPackageName(), 0);
        mVersionName = info.versionName;
        Log.i(TAG, this.getClass().getSimpleName() + " Spine server Test Application Version " + mVersionName);
    } catch (NameNotFoundException e) {
        Log.e(TAG, this.getClass().getSimpleName() + e.toString());
    }
}

From source file:org.envirocar.app.activity.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    readSavedState(savedInstanceState);// w  ww  .j a v  a2s. c  o  m

    this.setContentView(R.layout.main_layout);

    application = ((ECApplication) getApplication());

    preferences = PreferenceManager.getDefaultSharedPreferences(this);

    alwaysUpload = preferences.getBoolean(SettingsActivity.ALWAYS_UPLOAD, false);
    uploadOnlyInWlan = preferences.getBoolean(SettingsActivity.WIFI_UPLOAD, true);

    checkKeepScreenOn();

    actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setTitle("");

    // font stuff
    actionBarTitleID = Utils.getActionBarId();
    if (Utils.getActionBarId() != 0) {
        TextView view = (TextView) this.findViewById(actionBarTitleID);
        if (view != null) {
            view.setTypeface(TypefaceEC.Newscycle(this));
        }
    }

    actionBar.setLogo(getResources().getDrawable(R.drawable.actionbarlogo_with_padding));

    manager = getSupportFragmentManager();

    DashboardFragment initialFragment = new DashboardFragment();
    manager.beginTransaction().replace(R.id.content_frame, initialFragment, DASHBOARD_TAG).commit();

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerList = (ListView) findViewById(R.id.left_drawer);
    navDrawerAdapter = new NavAdapter();
    prepareNavDrawerItems();
    updateStartStopButton();
    drawerList.setAdapter(navDrawerAdapter);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, R.drawable.ic_drawer,
            R.string.open_drawer, R.string.close_drawer) {

        @Override
        public void onDrawerOpened(View drawerView) {
            prepareNavDrawerItems();
            super.onDrawerOpened(drawerView);
        }
    };

    drawer.setDrawerListener(actionBarDrawerToggle);
    drawerList.setOnItemClickListener(this);

    manager.executePendingTransactions();

    serviceStateReceiver = new AbstractBackgroundServiceStateReceiver() {
        @Override
        public void onStateChanged(ServiceState state) {
            serviceState = state;

            if (serviceState == ServiceState.SERVICE_STOPPED && trackMode == TRACK_MODE_AUTO) {
                /*
                 * we need to start the DeviceInRangeService
                 */
                startService(new Intent(getApplicationContext(), DeviceInRangeService.class));
            }

            updateStartStopButton();
        }
    };

    registerReceiver(serviceStateReceiver,
            new IntentFilter(AbstractBackgroundServiceStateReceiver.SERVICE_STATE));

    deviceDiscoveryStateReceiver = new AbstractBackgroundServiceStateReceiver() {

        @Override
        public void onStateChanged(ServiceState state) {
            if (state == ServiceState.SERVICE_DEVICE_DISCOVERY_PENDING) {
                discoveryTargetTime = deviceInRangeService.getNextDiscoveryTargetTime();
                invokeRemainingTimeThread();
            } else if (state == ServiceState.SERVICE_DEVICE_DISCOVERY_RUNNING) {

            }
        }
    };
    registerReceiver(deviceDiscoveryStateReceiver,
            new IntentFilter(AbstractBackgroundServiceStateReceiver.SERVICE_STATE));

    bluetoothStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateStartStopButton();
        }
    };

    registerReceiver(bluetoothStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

    settingsReceiver = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if (key.equals(SettingsActivity.BLUETOOTH_NAME)) {
                updateStartStopButton();
            }
            if (key.equals(SettingsActivity.CAR) || key.equals(SettingsActivity.CAR_HASH_CODE)) {
                updateStartStopButton();
            }
        }
    };

    preferences.registerOnSharedPreferenceChangeListener(settingsReceiver);

    errorInformationReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Fragment fragment = getSupportFragmentManager().findFragmentByTag(TROUBLESHOOTING_TAG);
            if (fragment == null) {
                fragment = new TroubleshootingFragment();
            }
            fragment.setArguments(intent.getExtras());
            getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
        }
    };

    registerReceiver(errorInformationReceiver, new IntentFilter(TroubleshootingFragment.INTENT));

    resolvePersistentSeenAnnouncements();

}

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {

    if (intent == null) {
        return START_STICKY;
    }//www .j  a  v  a  2  s .co  m

    String action = intent.getAction();

    if (Intent.ACTION_BATTERY_CHANGED.equals(action) || Intent.ACTION_BATTERY_LOW.equals(action)
            || Intent.ACTION_BATTERY_OKAY.equals(action)) {
        // ????

        mHostBatteryManager.setBatteryRequest(intent);

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostBatteryProfile.PROFILE_NAME,
                null, HostBatteryProfile.ATTRIBUTE_ON_BATTERY_CHANGE);
        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostBatteryProfile.setAttribute(mIntent, HostBatteryProfile.ATTRIBUTE_ON_BATTERY_CHANGE);
            Bundle battery = new Bundle();
            HostBatteryProfile.setLevel(battery, mHostBatteryManager.getBatteryLevel());
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    } else if (Intent.ACTION_POWER_CONNECTED.equals(action)
            || Intent.ACTION_POWER_DISCONNECTED.equals(action)) {
        // ????

        mHostBatteryManager.setBatteryRequest(intent);

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostBatteryProfile.PROFILE_NAME,
                null, HostBatteryProfile.ATTRIBUTE_ON_CHARGING_CHANGE);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostBatteryProfile.setAttribute(mIntent, HostBatteryProfile.ATTRIBUTE_ON_CHARGING_CHANGE);
            Bundle charging = new Bundle();

            if (Intent.ACTION_POWER_CONNECTED.equals(action)) {
                HostBatteryProfile.setCharging(charging, true);
            } else {
                HostBatteryProfile.setCharging(charging, false);
            }

            HostBatteryProfile.setBattery(mIntent, charging);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    } else if (action.equals("android.intent.action.NEW_OUTGOING_CALL")) {
        // Phone

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostPhoneProfile.PROFILE_NAME, null,
                HostPhoneProfile.ATTRIBUTE_ON_CONNECT);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostPhoneProfile.setAttribute(mIntent, HostPhoneProfile.ATTRIBUTE_ON_CONNECT);
            Bundle phoneStatus = new Bundle();
            HostPhoneProfile.setPhoneNumber(phoneStatus, intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER));
            HostPhoneProfile.setState(phoneStatus, CallState.START);
            HostPhoneProfile.setPhoneStatus(mIntent, phoneStatus);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    } else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)
            || WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
        // Wifi

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostConnectProfile.PROFILE_NAME,
                null, HostConnectProfile.ATTRIBUTE_ON_WIFI_CHANGE);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostConnectProfile.setAttribute(mIntent, HostConnectProfile.ATTRIBUTE_ON_WIFI_CHANGE);
            Bundle wifiConnecting = new Bundle();
            WifiManager wifiMgr = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
            HostConnectProfile.setEnable(wifiConnecting, wifiMgr.isWifiEnabled());
            HostConnectProfile.setConnectStatus(mIntent, wifiConnecting);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;

    } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {

        List<Event> events = EventManager.INSTANCE.getEventList(mDeviceId, HostConnectProfile.PROFILE_NAME,
                null, HostConnectProfile.ATTRIBUTE_ON_BLUETOOTH_CHANGE);

        for (int i = 0; i < events.size(); i++) {
            Event event = events.get(i);
            Intent mIntent = EventManager.createEventMessage(event);

            HostConnectProfile.setAttribute(mIntent, HostConnectProfile.ATTRIBUTE_ON_BLUETOOTH_CHANGE);
            Bundle bluetoothConnecting = new Bundle();
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            HostConnectProfile.setEnable(bluetoothConnecting, mBluetoothAdapter.isEnabled());
            HostConnectProfile.setConnectStatus(mIntent, bluetoothConnecting);
            getContext().sendBroadcast(mIntent);
        }

        return START_STICKY;
    }
    return super.onStartCommand(intent, flags, startId);
}