List of usage examples for android.bluetooth BluetoothAdapter getDefaultAdapter
public static synchronized BluetoothAdapter getDefaultAdapter()
From source file:com.kjsaw.alcosys.ibacapp.IBAC.java
public void initBluetooth(MODE mode) { // Get local Bluetooth adapter // if(BluetoothIBACService.isBLEsupported(IBAC.this)){ // final BluetoothManager bluetoothManager =(BluetoothManager) IBAC.this.getSystemService(Context.BLUETOOTH_SERVICE); // _bluetoothAdapter = bluetoothManager.getAdapter(); // }/*from w w w . j av a2s . c o m*/ // else _bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // If the adapter is null, then Bluetooth is not supported then exit if (_bluetoothAdapter == null) { Toast.makeText(this, getResources().getString(R.string.bt_not_supported), Toast.LENGTH_LONG).show(); finish(); android.os.Process.killProcess(android.os.Process.myPid()); return; } _iBACservice = new BluetoothIBACService(this, _handler, mode); InitializeAllServices(); }
From source file:com.wbtech.ums.UmsAgent.java
private static JSONObject getClientDataJSONObject(Context context) { TelephonyManager tm = (TelephonyManager) (context.getSystemService(Context.TELEPHONY_SERVICE)); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics displaysMetrics = new DisplayMetrics(); manager.getDefaultDisplay().getMetrics(displaysMetrics); LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); JSONObject clientData = new JSONObject(); try {//from w w w . j av a2s . c o m clientData.put("os_version", CommonUtil.getOsVersion(context)); clientData.put("platform", "android"); clientData.put("language", Locale.getDefault().getLanguage()); clientData.put("deviceid", tm.getDeviceId() == null ? "" : tm.getDeviceId());// clientData.put("appkey", CommonUtil.getAppKey(context)); clientData.put("resolution", displaysMetrics.widthPixels + "x" + displaysMetrics.heightPixels); clientData.put("ismobiledevice", true); clientData.put("phonetype", tm.getPhoneType());// clientData.put("imsi", tm.getSubscriberId()); clientData.put("network", CommonUtil.getNetworkTypeWIFI2G3G(context)); clientData.put("time", CommonUtil.getTime()); clientData.put("version", CommonUtil.getVersion(context)); clientData.put(UserIdentifier, CommonUtil.getUserIdentifier(context)); SCell sCell = CommonUtil.getCellInfo(context); clientData.put("mccmnc", sCell != null ? "" + sCell.MCCMNC : ""); clientData.put("cellid", sCell != null ? sCell.CID + "" : ""); clientData.put("lac", sCell != null ? sCell.LAC + "" : ""); clientData.put("modulename", Build.PRODUCT); clientData.put("devicename", CommonUtil.getDeviceName()); clientData.put("wifimac", wifiManager.getConnectionInfo().getMacAddress()); clientData.put("havebt", adapter == null ? false : true); clientData.put("havewifi", CommonUtil.isWiFiActive(context)); clientData.put("havegps", locationManager == null ? false : true); clientData.put("havegravity", CommonUtil.isHaveGravity(context));// LatitudeAndLongitude coordinates = CommonUtil.getLatitudeAndLongitude(context, UmsAgent.mUseLocationService); clientData.put("latitude", coordinates.latitude); clientData.put("longitude", coordinates.longitude); CommonUtil.printLog("clientData---------->", clientData.toString()); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return clientData; }
From source file:xj.property.ums.UmsAgent.java
public static JSONObject getClientDataJSONObject(Context context) { TelephonyManager tm = (TelephonyManager) (context.getSystemService(Context.TELEPHONY_SERVICE)); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics displaysMetrics = new DisplayMetrics(); manager.getDefaultDisplay().getMetrics(displaysMetrics); LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); JSONObject clientData = new JSONObject(); try {/* w w w . j a va2 s . c o m*/ clientData.put("os_version", CommonUtil.getOsVersion(context)); clientData.put("platform", "android"); clientData.put("language", Locale.getDefault().getLanguage()); clientData.put("deviceid", tm.getDeviceId() == null ? "" : tm.getDeviceId());// clientData.put("appkey", CommonUtil.getAppKey(context)); clientData.put("resolution", displaysMetrics.widthPixels + "x" + displaysMetrics.heightPixels); clientData.put("ismobiledevice", true); clientData.put("phonetype", tm.getPhoneType());// clientData.put("imsi", tm.getSubscriberId()); clientData.put("network", CommonUtil.getNetworkTypeWIFI2G3G(context)); clientData.put("time", CommonUtil.getTime()); clientData.put("version", CommonUtil.getVersion(context)); clientData.put(UserIdentifier, CommonUtil.getUserIdentifier(context)); SCell sCell = CommonUtil.getCellInfo(context); clientData.put("mccmnc", sCell != null ? "" + sCell.MCCMNC : ""); clientData.put("cellid", sCell != null ? sCell.CID + "" : ""); clientData.put("lac", sCell != null ? sCell.LAC + "" : ""); clientData.put("modulename", Build.PRODUCT); clientData.put("devicename", CommonUtil.getDeviceName()); clientData.put("wifimac", wifiManager.getConnectionInfo().getMacAddress()); clientData.put("havebt", adapter == null ? false : true); clientData.put("havewifi", CommonUtil.isWiFiActive(context)); clientData.put("havegps", locationManager == null ? false : true); clientData.put("havegravity", CommonUtil.isHaveGravity(context));// LatitudeAndLongitude coordinates = CommonUtil.getLatitudeAndLongitude(context, UmsAgent.mUseLocationService); clientData.put("latitude", coordinates.latitude); clientData.put("longitude", coordinates.longitude); CommonUtil.printLog("clientData---------->", clientData.toString()); } catch (JSONException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return clientData; }
From source file:com.nest5.businessClient.Initialactivity.java
/** * Begins the activity.//from w w w . ja v a 2s . com */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.savedInstanceState = savedInstanceState; getWindow().setFormat(PixelFormat.RGBA_8888); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER); BugSenseHandler.initAndStartSession(Initialactivity.this, "1a5a6af1"); setContentView(R.layout.swipe_view); checkLogin(); // add necessary intent values to be matched. intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); channel = manager.initialize(this, getMainLooper(), null); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); dbHelper = new MySQLiteHelper(this); ingredientCategoryDatasource = new IngredientCategoryDataSource(dbHelper); db = ingredientCategoryDatasource.open(); ingredientCategories = ingredientCategoryDatasource.getAllIngredientCategory(); // ingredientCategoryDatasource.close(); productCategoryDatasource = new ProductCategoryDataSource(dbHelper); productCategoryDatasource.open(db); productsCategories = productCategoryDatasource.getAllProductCategory(); taxDataSource = new TaxDataSource(dbHelper); taxDataSource.open(db); taxes = taxDataSource.getAllTax(); unitDataSource = new UnitDataSource(dbHelper); unitDataSource.open(db); units = unitDataSource.getAllUnits(); ingredientDatasource = new IngredientDataSource(dbHelper); ingredientDatasource.open(db); ingredientes = ingredientDatasource.getAllIngredient(); productDatasource = new ProductDataSource(dbHelper); productDatasource.open(db); productos = productDatasource.getAllProduct(); comboDatasource = new ComboDataSource(dbHelper); comboDatasource.open(db); combos = comboDatasource.getAllCombos(); saleDataSource = new SaleDataSource(dbHelper); saleDataSource.open(db); saleList = saleDataSource.getAllSales(); syncRowDataSource = new SyncRowDataSource(dbHelper); syncRowDataSource.open(db); Calendar today = Calendar.getInstance(); Calendar tomorrow = Calendar.getInstance(); today.set(Calendar.HOUR, 0); today.set(Calendar.HOUR_OF_DAY, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); today.set(Calendar.MILLISECOND, 0); tomorrow.roll(Calendar.DATE, 1); tomorrow.set(Calendar.HOUR, 0); tomorrow.set(Calendar.HOUR_OF_DAY, 0); tomorrow.set(Calendar.MINUTE, 0); tomorrow.set(Calendar.SECOND, 0); tomorrow.set(Calendar.MILLISECOND, 0); init = today.getTimeInMillis(); end = tomorrow.getTimeInMillis(); //Log.d(TAG, today.toString()); //Log.d(TAG, tomorrow.toString()); Calendar now = Calendar.getInstance(); now.setTimeInMillis(System.currentTimeMillis()); //Log.d(TAG, now.toString()); //Log.d(TAG, "Diferencia entre tiempos: " + String.valueOf(end - init)); salesFromToday = saleDataSource.getAllSalesWithin(init, end); updateRegistrables(); // ingredientDatasource.close(); mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mDemoCollectionPagerAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { // When swiping between pages, select the // corresponding tab. getActionBar().setSelectedNavigationItem(position); } }); final ActionBar actionBar = getActionBar(); // Specify that tabs should be displayed in the action bar. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create a tab listener that is called when the user changes tabs. ActionBar.TabListener tabListener = new ActionBar.TabListener() { @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } }; Tab homeTab = actionBar.newTab().setText("Inicio").setTabListener(tabListener); Tab ordersTab = actionBar.newTab().setText("rdenes").setTabListener(tabListener); /*Tab dailyTab = actionBar.newTab().setText("Registros") .setTabListener(tabListener); Tab inventoryTab = actionBar.newTab().setText("Inventarios") .setTabListener(tabListener);*/ Tab nest5ReadTab = actionBar.newTab().setText("Nest5").setTabListener(tabListener); actionBar.addTab(homeTab, true); actionBar.addTab(ordersTab, false); //actionBar.addTab(dailyTab, false); //actionBar.addTab(inventoryTab, false); actionBar.addTab(nest5ReadTab, false); currentOrder = new LinkedHashMap<Registrable, Integer>(); inTableRegistrable = new ArrayList<Registrable>(); savedOrders = new LinkedHashMap<String, LinkedHashMap<Registrable, Integer>>(); cookingOrders = new LinkedList<LinkedHashMap<Registrable, Integer>>(); //cookingOrdersMethods = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, String>(); cookingOrdersDelivery = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Integer>(); cookingOrdersTogo = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Integer>(); //cookingOrdersTip = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Integer>(); //cookingOrdersDiscount = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Double>(); cookingOrdersTimes = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Long>(); cookingOrdersTable = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, CurrentTable<Table, Integer>>(); openTables = new LinkedList<CurrentTable<Table, Integer>>(); //cookingOrdersReceived = new LinkedHashMap<LinkedHashMap<Registrable, Integer>, Double>(); frases = getResources().getStringArray(R.array.phrases); timer = new Timer(); deviceID = DeviceID.getDeviceId(mContext); //////Log.i("AACCCAAAID",deviceID); BebasFont = Typeface.createFromAsset(getAssets(), "fonts/BebasNeue.otf"); VarelaFont = Typeface.createFromAsset(getAssets(), "fonts/Varela-Regular.otf"); // Lector de tarjetas magnticas mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); //mReader = new ACR31Reader(mAudioManager); /* Initialize the reset progress dialog */ mResetProgressDialog = new ProgressDialog(mContext); // ACR31 RESET CALLBACK /*mReader.setOnResetCompleteListener(new ACR31Reader.OnResetCompleteListener() { //hola como estas @Override public void onResetComplete(ACR31Reader reader) { if (mSettingSleepTimeout) { mGettingStatus = true; mReader.setSleepTimeout(mSleepTimeout); mSettingSleepTimeout = false; } runOnUiThread(new Runnable() { @Override public void run() { mResetProgressDialog.dismiss(); }; }); } });*/ /* Set the raw data callback. */ /*mReader.setOnRawDataAvailableListener(new ACR31Reader.OnRawDataAvailableListener() { @Override public void onRawDataAvailable(ACR31Reader reader, byte[] rawData) { ////Log.i("MISPRUEBAS", "setOnRawDataAvailableListener"); final String hexString = toHexString(rawData) + (reader.verifyData(rawData) ? " (Checksum OK)" : " (Checksum Error)"); ////Log.i("MISPRUEBAS", hexString); if (reader.verifyData(rawData)) { runOnUiThread(new Runnable() { @Override public void run() { mResetProgressDialog .setMessage("Solicitando Informacin al Servidor..."); mResetProgressDialog.setCancelable(false); mResetProgressDialog.setIndeterminate(true); mResetProgressDialog.show(); } }); SharedPreferences prefs = Util .getSharedPreferences(mContext); restService = new RestService(recievePromoandUserHandler, mContext, Setup.PROD_URL + "/company/initMagneticStamp"); restService.addParam("company", prefs.getString(Setup.COMPANY_ID, "0")); restService.addParam("magnetic5", hexString); restService.setCredentials("apiadmin", Setup.apiKey); try { restService.execute(RestService.POST); } catch (Exception e) { e.printStackTrace(); ////Log.i("MISPRUEBAS", "Error empezando request"); } } } });*/ }
From source file:ibme.sleepap.recording.SignalsRecorder.java
/** * Called when the activity is first created. onStart() is called * immediately afterwards./*w ww . j ava 2 s . c o m*/ */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.signals_recorder); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // Log both handled and unhandled issues. if (sharedPreferences.getBoolean(Constants.PREF_WRITE_LOG, Constants.DEFAULT_WRITE_LOG)) { String bugDirPath = Environment.getExternalStorageDirectory().toString() + "/" + getString(R.string.app_name) + "/" + Constants.FILENAME_LOG_DIRECTORY; File bugDir = new File(bugDirPath); if (!bugDir.exists()) { bugDir.mkdirs(); } String handledFileName = bugDirPath + "/logcat" + System.currentTimeMillis() + ".trace"; String unhandledFileName = bugDirPath + "/unhandled" + System.currentTimeMillis() + ".trace"; // Log any warning or higher, and write it to handledFileName. String[] cmd = new String[] { "logcat", "-f", handledFileName, "*:W" }; try { Runtime.getRuntime().exec(cmd); } catch (IOException e1) { Log.e(Constants.CODE_APP_TAG, "Error creating bug files", e1); } Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(unhandledFileName)); } bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); extras = getIntent().getBundleExtra(Constants.EXTRA_RECORDING_SETTINGS); actigraphyEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_ACTIGRAPHY, false); audioEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_AUDIO, false); ppgEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_PPG, false); dateTimeString = DateFormat.format(Constants.PARAM_DATE_FORMAT, System.currentTimeMillis()).toString(); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); String appDirPath = Environment.getExternalStorageDirectory().toString() + "/" + getString(R.string.app_name); filesDirPath = appDirPath + "/" + dateTimeString + "/"; lastAccelerometerRecordedTime = 0; lastPositionChangeTime = System.currentTimeMillis(); PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.CODE_APP_TAG); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); actigraphyQueue = new LinkedList<Double>(); positionDisplay = (TextView) findViewById(R.id.position); recordingSign = (ImageView) findViewById(R.id.recordingSign); for (int i = 0; i < 5; ++i) { totalPositionTime[i] = 0; } // Battery check receiver. registerReceiver(this.batteryLevelReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); // Button to stop the recording. Button stopButton = (Button) findViewById(R.id.buttonStop); stopButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View viewNext) { stopRecording(); } }); // Button to reconnect the bluetooth. reconnectButton = (Button) findViewById(R.id.reconnectButton); reconnectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View viewNext) { String macAddress = sharedPreferences.getString(Constants.PREF_MAC_ADDRESS, Constants.DEFAULT_MAC_ADDRESS); noninManager = null; noninManager = new NoninManager(getApplicationContext(), bluetoothAdapter, macAddress, new PpgHandler(SignalsRecorder.this)); noninManager.start(); reconnectButton.setEnabled(false); reconnectButton.setClickable(false); } }); // Create a folder for the recordings, and delete any extra recordings. File dir = new File(filesDirPath); if (!dir.exists()) { dir.mkdirs(); File appDir = new File(appDirPath); // Create a list of recordings in the app directory. These // are named by the date on which they were formed and so can be in // date order (earliest first). String[] recordingDirs = appDir.list(); Arrays.sort(recordingDirs); // How many more recordings do we have in the app directory than are // specified in the settings? Should account for questionnaires // file, // which must exist for the user to have gotten to this stage // (checklist). int numberRecordings = 0; for (String folderOrFileName : recordingDirs) { if (!folderOrFileName.equals(Constants.FILENAME_QUESTIONNAIRE) && !folderOrFileName.equals(Constants.FILENAME_LOG_DIRECTORY) && !folderOrFileName.equals(Constants.FILENAME_FEEDBACK_DIRECTORY)) { numberRecordings++; } } int extraFiles = numberRecordings - Integer.parseInt(sharedPreferences .getString(Constants.PREF_NUMBER_RECORDINGS, Constants.DEFAULT_NUMBER_RECORDINGS)); if (extraFiles > 0) { // Too many recordings. Delete the earliest n, where n is the // number of extra files. boolean success; int nDeleted = 0; for (String candidateFolderName : recordingDirs) { if (nDeleted >= extraFiles) { // We've deleted enough already. break; } if (candidateFolderName.equals(Constants.FILENAME_QUESTIONNAIRE) || candidateFolderName.equals(Constants.FILENAME_LOG_DIRECTORY) || candidateFolderName.equals(Constants.FILENAME_FEEDBACK_DIRECTORY)) { // Don't delete questionnaire file or log/feedback // directory. continue; } // See if the path is a directory, and skip it if it isn't. File candidateFolder = new File(appDir, candidateFolderName); if (!candidateFolder.isDirectory()) { continue; } // If we've got to this stage, the file is the earliest // recording and should be deleted. Delete files in // recording first. success = Utils.deleteDirectory(candidateFolder); if (success) { nDeleted++; } } } } // Copy latest questionnaire File try { File latestQuestionnaireFile = new File(appDirPath, Constants.FILENAME_QUESTIONNAIRE); InputStream in = new FileInputStream(latestQuestionnaireFile); OutputStream out = new FileOutputStream(new File(filesDirPath, Constants.FILENAME_QUESTIONNAIRE)); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (FileNotFoundException e) { Log.e(Constants.CODE_APP_TAG, "FileNotFoundException copying Questionnaire file."); } catch (IOException e) { Log.e(Constants.CODE_APP_TAG, "IOException copying Questionnaire file."); } // Create txt files. orientationFile = new File(filesDirPath, Constants.FILENAME_ORIENTATION); accelerationFile = new File(filesDirPath, Constants.FILENAME_ACCELERATION_RAW); actigraphyFile = new File(filesDirPath, Constants.FILENAME_ACCELERATION_PROCESSED); audioProcessedFile = new File(filesDirPath, Constants.FILENAME_AUDIO_PROCESSED); bodyPositionFile = new File(filesDirPath, Constants.FILENAME_POSITION); ppgFile = new File(filesDirPath, Constants.FILENAME_PPG); spo2File = new File(filesDirPath, Constants.FILENAME_SPO2); audioRawFile = new File(filesDirPath, Constants.FILENAME_AUDIO_RAW); /** Recording starts here. */ // Log start time so recording can begin in 30 minutes. startTime = Calendar.getInstance(Locale.getDefault()); finishRecordingFlag = false; recordingStartDelayMs = Constants.CONST_MILLIS_IN_MINUTE * Integer.parseInt(sharedPreferences .getString(Constants.PREF_RECORDING_START_DELAY, Constants.DEFAULT_RECORDING_START_DELAY)); recordingDurationMs = Constants.CONST_MILLIS_IN_MINUTE * Integer.parseInt(sharedPreferences .getString(Constants.PREF_RECORDING_DURATION, Constants.DEFAULT_RECORDING_DURATION)); if (recordingStartDelayMs > 0) { startRecordingFlag = false; AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); dialogBuilder.setTitle(getString(R.string.delayAlertTitle)) .setMessage(getString(R.string.delayAlertMessage1) + " " + sharedPreferences.getString(Constants.PREF_RECORDING_START_DELAY, Constants.DEFAULT_RECORDING_START_DELAY) + " " + getString(R.string.delayAlertMessage2)) .setPositiveButton(getString(R.string.ok), null); delayAlertDialog = dialogBuilder.create(); delayAlertDialog.show(); } else { startRecordingFlag = true; // Notify user Intent notificationIntent = new Intent(SignalsRecorder.this, SignalsRecorder.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); if (sharedPreferences.getBoolean(Constants.PREF_NOTIFICATIONS, Constants.DEFAULT_NOTIFICATIONS)) { NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()) .setSmallIcon(R.drawable.notification_icon) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.deviceaccessmic)) .setContentTitle("SleepAp").setContentText(getString(R.string.startedRecordingNotification)) .setAutoCancel(false).setOngoing(true).setContentIntent(pendingIntent); notificationManager.notify(Constants.CODE_APP_NOTIFICATION_ID, builder.build()); recordingSign.setVisibility(View.VISIBLE); } } // Start audio recording. if (audioEnabled) { extAudioRecorder = new ExtAudioRecorder(this); extAudioRecorder.setOutputFile(audioRawFile); extAudioRecorder.setShouldWrite(startRecordingFlag); extAudioRecorder.setAudioProcessedFile(audioProcessedFile); extAudioRecorder.prepare(); extAudioRecorder.start(); } // Start PPG recording. if (ppgEnabled && bluetoothAdapter != null) { String macAddress = sharedPreferences.getString(Constants.PREF_MAC_ADDRESS, Constants.DEFAULT_MAC_ADDRESS); noninManager = new NoninManager(this, bluetoothAdapter, macAddress, new PpgHandler(SignalsRecorder.this)); noninManager.start(); } // Start actigraphy recording. if (actigraphyEnabled) { sensorManager.registerListener(this, accelerometer, 1000000 / (Constants.PARAM_SAMPLERATE_ACCELEROMETER * Constants.PARAM_UPSAMPLERATE_ACCELEROMETER)); sensorManager.registerListener(this, magnetometer, 1000000 / Constants.PARAM_SAMPLERATE_ACCELEROMETER); } wakeLock.acquire(); // Set up listener so that if Bluetooth connection is lost we set give // the user an option to reconnect. if (ppgEnabled) { IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(bluetoothDisconnectReceiver, filter); } // Start graphs update. graphUpdateTask = new UserInterfaceUpdater(); graphUpdateTask.execute(); }
From source file:edu.cmu.mpcs.dashboard.TagViewer.java
private String bluetoothSetting(String settingString) { /*/*from w ww . j a v a 2s . c om*/ * Enable/Disable bluetooth */ if (settingString.contains("bluetooth")) { BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (settingString.contains("bluetooth:On")) { mBluetoothAdapter.enable(); return ("Bluetooth turned On\n"); } else { mBluetoothAdapter.disable(); return ("Bluetooth turned Off\n"); } } return (""); }
From source file:com.zpci.firstsignhairclipdemo.MainActivity.java
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_SELECT_DEVICE: //When the DeviceListActivity return, with the selected device address if (resultCode == Activity.RESULT_OK && data != null) { String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE); mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress); Log.d(TAG, "... onActivityResultdevice.address==" + mDevice + "mserviceValue" + mService); ((TextView) findViewById(R.id.deviceName)).setText(mDevice.getName() + " - connecting"); mService.connect(deviceAddress); }/*from w w w.j a v a2 s . com*/ break; case REQUEST_ENABLE_BT: // When the request to enable Bluetooth returns if (resultCode == Activity.RESULT_OK) { Toast.makeText(this, "Bluetooth has turned on ", Toast.LENGTH_SHORT).show(); } else { // User did not enable Bluetooth or an error occurred Log.d(TAG, "BT not enabled"); Toast.makeText(this, "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show(); finish(); } break; case REQUEST_DIAG_CMD: if (resultCode == Activity.RESULT_OK) { byte[] value = data.getByteArrayExtra("cmd"); Log.d(TAG, "Diag command request success. length = " + value.length + ", 0x" + Integer.toHexString(value[0] & 0xff) + ", " + value[0]); if (value[0] == (byte) 0x05) { //alarm arm/disarm if (value[1] == (byte) 0x00) { armed = true; alarmsent = false; adStream.reset(); // reset audio data buffer expectedAudioSamples = ALARMAUDIOSAMPLES; // set to default number of samples SensorStream.reset(); // reset sensor data buffer expectedSensorSamples = ALARMSENSORSAMPLES; // set to default } else armed = false; } try { mService.writeRXCharacteristic(value); } catch (Exception e) { Log.e(TAG, e.toString()); } ; //Update the log with time stamp and message sent String msg = ""; for (int i = 0; i < value.length; i++) { msg = msg + "0x" + Integer.toHexString(value[i] & 0xff) + " "; } String currentDateTimeString = DateFormat.getTimeInstance().format(new Date()); listAdapter.add("[" + currentDateTimeString + "] TX: " + msg); messageListView.smoothScrollToPosition(listAdapter.getCount() - 1); } else { Log.d(TAG, "Diag command request result fail"); } break; default: Log.e(TAG, "bad activity result request code"); break; } }
From source file:com.github.akinaru.hcidebugger.activity.HciDebuggerActivity.java
/** * Activate/Desactivate snoop file log//from w ww .j a v a2 s . c o m * * @param state true if snoop file log is activated, false elsewhere */ public void configSnoopFile(boolean state) { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); Method[] adapterMethods = adapter.getClass().getDeclaredMethods(); for (Method method : adapterMethods) { if (method.getName().equals("configHciSnoopLog")) { Log.v(TAG, "activating snoop file log"); try { boolean ret = (boolean) method.invoke(adapter, state); Log.v(TAG, "configSnoop return with state " + ret); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } }
From source file:com.plusot.senselib.SenseMain.java
@SuppressWarnings("deprecation") public void showPopupDialog(int dialogId, int viewId, String[] items) {// , if (!alive) { if (dialogId == STEP_POPUP) popupToShow = STEP_POPUP;//w w w.j a v a 2s .c o m return; } int iEnd = 3; int timeOut = 0; int defaultChoice = 0; boolean cancelable = true; popupToShow = -1; String title = null; Map<String, String> lookup = null; if (items == null) items = getResources().getStringArray(R.array.value_popup_dialog_items); switch (dialogId) { case VALUE_POPUP: title = getString(R.string.valuepopup); items = getResources().getStringArray(R.array.value_popup_dialog_items); if (viewHasValue(viewId)) { popupValue = viewGetCurrentValue(viewId); title = popupValue.getValueType(this); if (popupValue.getValueType().equals(ValueType.POWER)) { items = Arrays.copyOf(items, items.length + 1); items[items.length - 1] = getString(R.string.calibrate); } else if (popupValue.getValueType().equals(ValueType.SLOPE)) { items = Arrays.copyOf(items, items.length + 1); items[items.length - 1] = getString(R.string.set_level); } } break; case VALUESELECT_POPUP: title = getString(R.string.valuepopup); items = Value.getValuePopupList(this, PreferenceKey.XTRAVALUES.isTrue()); break; case UNIT_POPUP: title = getString(R.string.unitpopup); if (items == null || items.length == 0) ToastHelper.showToastLong(R.string.no_unit_choice); break; case YEAR_POPUP: title = getString(R.string.yearpopup); if (fileExplorer == null) { items = null; } else { items = fileExplorer.getYears(); } if (items == null || items.length == 0) { ToastHelper.showToastLong(R.string.no_year_choice); return; } else if (items.length > 1) { break; } logYear = items[0]; dialogId = MONTH_POPUP; case MONTH_POPUP: title = getString(R.string.monthpopup); if (fileExplorer == null) { items = null; } else { logMonths = fileExplorer.getMonths(logYear); items = FileExplorer.getMonths(logYear, logMonths); } if (items == null || items.length == 0) { ToastHelper.showToastLong(getString(R.string.no_month_choice, logYear)); return; } else if (items.length > 1) { break; } logMonth = logMonths[0]; LLog.d(Globals.TAG, CLASSTAG + ".showPopupDialog: logMonth = " + logMonth); dialogId = DAY_POPUP; case DAY_POPUP: title = getString(R.string.daypopup); if (fileExplorer == null) { items = null; } else { logDays = fileExplorer.getDays(logYear, logMonth); items = FileExplorer.getDays(logYear, DateUtils.getMonthString(logMonth - 1, DateUtils.LENGTH_LONG), logDays); } break; case TIMES_POPUP: title = getString(R.string.timespopup); if (fileExplorer == null) { items = null; } else { items = fileExplorer.getTimes(logYear, logMonth, logDay); } break; case MOVESTART_POPUP: lastAskForActivityStart = System.currentTimeMillis(); if (moveStartBusy) { title = null; } else { moveStartBusy = true; title = getString(R.string.movestartpopup); items = getResources().getStringArray(R.array.start_popup_dialog_items); if (SenseGlobals.stopState.equals(SenseGlobals.StopState.STOP)) items = Arrays.copyOfRange(items, 1, iEnd); else items = Arrays.copyOfRange(items, 0, iEnd); cancelable = false; } break; case STEP_POPUP: lastAskForActivityStart = System.currentTimeMillis(); timeOut = 10000; switch (step) { case 0: title = getString(R.string.recoverypopup); items = getResources().getStringArray(R.array.fitnessorrecovery_popup_dialog_items); cancelable = false; break; case 1: title = getString(R.string.step1settingspopup); List<String> list = new ArrayList<String>(); String profile = PreferenceKey.getProfileName(); list.add(getString(R.string.step1_bikeprofile, profile)); //list.add(getString(R.string.popitem_wheelcirumference, prefs.getWheelCirc())); if (PreferenceKey.USEPAIRING.isTrue()) list.add(getString(R.string.popitem_pairing_on, profile)); else list.add(getString(R.string.popitem_pairing_off, profile)); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null && adapter.isEnabled()) list.add(getString(R.string.popitem_bluetooth_on)); else list.add(getString(R.string.popitem_bluetooth_off)); list.add(getString(R.string.step_continue)); items = list.toArray(new String[0]); cancelable = false; break; case 2: if (PreferenceKey.XTRAVALUES.isTrue()) { title = getString(R.string.startpopup); iEnd = 3; } else { title = getString(R.string.step2startpopup); iEnd = 4; } cancelable = false; if (title == null) title = getString(R.string.startpopup); items = getResources().getStringArray(R.array.start_popup_dialog_items); if (SenseGlobals.stopState.equals(SenseGlobals.StopState.STOP)) { items = Arrays.copyOfRange(items, 1, iEnd); startOptions = 3; } else { items = Arrays.copyOfRange(items, 0, iEnd); startOptions = 4; } break; } break; case START_POPUP: lastAskForActivityStart = System.currentTimeMillis(); if (title == null) title = getString(R.string.startpopup); timeOut = 10000; items = getResources().getStringArray(R.array.start_popup_dialog_items); if (SenseGlobals.stopState.equals(SenseGlobals.StopState.STOP)) items = Arrays.copyOfRange(items, 1, iEnd); else items = Arrays.copyOfRange(items, 0, iEnd); break; case ARGOSSTOP_POPUP: cancelable = false; switch (argosStopStep) { case 0: title = getString(R.string.intensitypopup); items = getResources().getStringArray(R.array.intensity_popup_dialog_items); break; case 1: title = getString(R.string.fitnesspopup); items = getResources().getStringArray(R.array.fitnessorrecovery_popup_dialog_items); break; } break; case FULLSTOP_POPUP: lastAskForActivityStart = System.currentTimeMillis(); title = getString(R.string.stoppopup); items = getResources().getStringArray(R.array.stop_popup_dialog_items); break; case STOP_POPUP: lastAskForActivityStart = System.currentTimeMillis(); title = getString(R.string.stoppopup); items = getResources().getStringArray(R.array.stop_popup_dialog_items); break; case SHARE_POPUP: title = getString(R.string.sharepopup); items = getResources().getStringArray(R.array.share_popup_dialog_items); if (Globals.testing.isNoTest()) items = Arrays.copyOf(items, items.length - 1); break; case INTERVAL_POPUP: title = getString(R.string.menu_interval); items = getResources().getStringArray(R.array.interval_popup_dialog_items); break; case GPX_POPUP: title = getString(R.string.menu_gpx); FileExplorer.FileList list = FileExplorer.getFileList( new String[] { Globals.getDataPath(), Globals.getDownloadPath(), SenseGlobals.getGpxPath() }, new String[] { ".gpx" }, false); items = list.items; lookup = list.lookup; break; } if (title != null && items != null && items.length > 0) { if (!PopupDialog.showPopupDialog(getFragmentManager(), title, dialogId, viewId, items, lookup, cancelable, timeOut, defaultChoice) && dialogId == STEP_POPUP) popupToShow = STEP_POPUP; } }
From source file:edu.stanford.mobisocial.dungbeetle.NearbyActivity.java
private void findBluetooth() { if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) { Intent bt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(bt, RESULT_BT_ENABLE); return;//from w w w . ja v a 2 s. c o m } // Create a BroadcastReceiver for ACTION_FOUND final IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); final BroadcastReceiver receiver = new BroadcastReceiver() { public void onReceive(final Context context, final Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { new Thread() { public void run() { BluetoothBeacon.OnDiscovered discovered = new BluetoothBeacon.OnDiscovered() { @Override public void onDiscovered(final byte[] data) { runOnUiThread(new Runnable() { @Override public void run() { try { JSONObject obj = new JSONObject(new String(data)); mNearbyList.add( new NearbyItem(NearbyItem.Type.FEED, obj.getString("name"), Uri.parse(obj.getString("dynuri")), null)); mAdapter.notifyDataSetChanged(); } catch (JSONException e) { Log.e(TAG, "Error getting group info over bluetooth", e); } } }); } }; // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); BluetoothBeacon.discover(NearbyActivity.this, device, discovered); }; }.start(); } if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { unregisterReceiver(this); } } }; registerReceiver(receiver, filter); // Don't forget to unregister during // onDestroy BluetoothAdapter.getDefaultAdapter().startDiscovery(); Toast.makeText(this, "Scanning Bluetooth...", 500).show(); }