List of usage examples for android.content Context SENSOR_SERVICE
String SENSOR_SERVICE
To view the source code for android.content Context SENSOR_SERVICE.
Click Source Link
From source file:com.zainsoft.ramzantimetable.QiblaActivity.java
private void registerListeners() { SharedPreferences perfs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Sensor gsensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); Sensor msensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mSensorManager.registerListener(qiblaManager, gsensor, SensorManager.SENSOR_DELAY_GAME); mSensorManager.registerListener(qiblaManager, msensor, SensorManager.SENSOR_DELAY_GAME); schedule();// w w w . j a v a 2 s . com isRegistered = true; }
From source file:com.vonglasow.michael.satstat.ui.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { Context c = getApplicationContext(); File dumpDir = c.getExternalFilesDir(null); DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.ROOT); fmt.setTimeZone(TimeZone.getTimeZone("UTC")); String fileName = String.format("satstat-%s.log", fmt.format(new Date(System.currentTimeMillis()))); File dumpFile = new File(dumpDir, fileName); PrintStream s;// ww w .ja v a 2s.co m try { InputStream buildInStream = getResources().openRawResource(R.raw.build); s = new PrintStream(dumpFile); s.append("SatStat build: "); int i; try { i = buildInStream.read(); while (i != -1) { s.write(i); i = buildInStream.read(); } buildInStream.close(); } catch (IOException e1) { e1.printStackTrace(); } s.append("\n\n"); e.printStackTrace(s); s.flush(); s.close(); Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri contentUri = Uri.fromFile(dumpFile); mediaScanIntent.setData(contentUri); c.sendBroadcast(mediaScanIntent); } catch (FileNotFoundException e2) { e2.printStackTrace(); } defaultUEH.uncaughtException(t, e); } }); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mSharedPreferences.registerOnSharedPreferenceChangeListener(this); prefUnitType = mSharedPreferences.getBoolean(Const.KEY_PREF_UNIT_TYPE, prefUnitType); prefKnots = mSharedPreferences.getBoolean(Const.KEY_PREF_KNOTS, prefKnots); prefCoord = Integer .valueOf(mSharedPreferences.getString(Const.KEY_PREF_COORD, Integer.toString(prefCoord))); prefUtc = mSharedPreferences.getBoolean(Const.KEY_PREF_UTC, prefUtc); prefCid = mSharedPreferences.getBoolean(Const.KEY_PREF_CID, prefCid); prefCid2 = mSharedPreferences.getBoolean(Const.KEY_PREF_CID2, prefCid2); prefWifiSort = Integer .valueOf(mSharedPreferences.getString(Const.KEY_PREF_WIFI_SORT, Integer.toString(prefWifiSort))); prefMapOffline = mSharedPreferences.getBoolean(Const.KEY_PREF_MAP_OFFLINE, prefMapOffline); prefMapPath = mSharedPreferences.getString(Const.KEY_PREF_MAP_PATH, prefMapPath); ActionBar actionBar = getSupportActionBar(); setContentView(R.layout.activity_main); // Find out default screen orientation Configuration config = getResources().getConfiguration(); WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); int rot = wm.getDefaultDisplay().getRotation(); isWideScreen = (config.orientation == Configuration.ORIENTATION_LANDSCAPE && (rot == Surface.ROTATION_0 || rot == Surface.ROTATION_180) || config.orientation == Configuration.ORIENTATION_PORTRAIT && (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270)); Log.d(TAG, "isWideScreen=" + Boolean.toString(isWideScreen)); // Create the adapter that will return a fragment for each of the // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); Context ctx = new ContextThemeWrapper(getApplication(), R.style.AppTheme); mTabLayout = new TabLayout(ctx); LinearLayout.LayoutParams mTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); mTabLayout.setLayoutParams(mTabLayoutParams); for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { TabLayout.Tab newTab = mTabLayout.newTab(); newTab.setIcon(mSectionsPagerAdapter.getPageIcon(i)); mTabLayout.addTab(newTab); } actionBar.setDisplayShowCustomEnabled(true); actionBar.setCustomView(mTabLayout); mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager)); mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout)); // This is needed by the mapsforge library. AndroidGraphicFactory.createInstance(this.getApplication()); // Get system services for event delivery locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mOrSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); mAccSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mGyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); mMagSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mLightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); mProximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); mPressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); mHumiditySensor = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY); mTempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); }
From source file:com.landenlabs.all_devtool.SystemFragment.java
public void updateList() { // Time today = new Time(Time.getCurrentTimezone()); // today.setToNow(); // today.format(" %H:%M:%S") Date dt = new Date(); m_titleTime.setText(m_timeFormat.format(dt)); boolean expandAll = m_list.isEmpty(); m_list.clear();//from w w w . j a v a2 s. c o m // Swap colors int color = m_rowColor1; m_rowColor1 = m_rowColor2; m_rowColor2 = color; ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE); try { String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(), Settings.Secure.ANDROID_ID); addBuild("Android ID", androidIDStr); try { AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext()); final String adIdStr = adInfo.getId(); final boolean isLAT = adInfo.isLimitAdTrackingEnabled(); addBuild("Ad ID", adIdStr); } catch (IOException e) { // Unrecoverable error connecting to Google Play services (e.g., // the old version of the service doesn't support getting AdvertisingId). } catch (GooglePlayServicesNotAvailableException e) { // Google Play services is not available entirely. } /* try { InstanceID instanceID = InstanceID.getInstance(getContext()); if (instanceID != null) { // Requires a Google Developer project ID. String authorizedEntity = "<need to make this on google developer site>"; instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); addBuild("Instance ID", instanceID.getId()); } } catch (Exception ex) { } */ ConfigurationInfo info = actMgr.getDeviceConfigurationInfo(); addBuild("OpenGL", info.getGlEsVersion()); } catch (Exception ex) { m_log.e(ex.getMessage()); } try { long heapSize = Debug.getNativeHeapSize(); // long maxHeap = Runtime.getRuntime().maxMemory(); // ConfigurationInfo cfgInfo = actMgr.getDeviceConfigurationInfo(); int largHeapMb = actMgr.getLargeMemoryClass(); int heapMb = actMgr.getMemoryClass(); MemoryInfo memInfo = new MemoryInfo(); actMgr.getMemoryInfo(memInfo); final String sFmtMB = "%.2f MB"; Map<String, String> listStr = new TreeMap<String, String>(); listStr.put("Mem Available (now)", String.format(sFmtMB, (double) memInfo.availMem / MB)); listStr.put("Mem LowWhenOnlyAvail", String.format(sFmtMB, (double) memInfo.threshold / MB)); if (Build.VERSION.SDK_INT >= 16) { listStr.put("Mem Installed", String.format(sFmtMB, (double) memInfo.totalMem / MB)); } listStr.put("Heap (this app)", String.format(sFmtMB, (double) heapSize / MB)); listStr.put("HeapMax (default)", String.format(sFmtMB, (double) heapMb)); listStr.put("HeapMax (large)", String.format(sFmtMB, (double) largHeapMb)); addBuild("Memory...", listStr); } catch (Exception ex) { m_log.e(ex.getMessage()); } try { List<ProcessErrorStateInfo> procErrList = actMgr.getProcessesInErrorState(); int errCnt = (procErrList == null ? 0 : procErrList.size()); procErrList = null; // List<RunningAppProcessInfo> procList = actMgr.getRunningAppProcesses(); int procCnt = actMgr.getRunningAppProcesses().size(); int srvCnt = actMgr.getRunningServices(100).size(); Map<String, String> listStr = new TreeMap<String, String>(); listStr.put("#Processes", String.valueOf(procCnt)); listStr.put("#Proc With Err", String.valueOf(errCnt)); listStr.put("#Services", String.valueOf(srvCnt)); // Requires special permission // int taskCnt = actMgr.getRunningTasks(100).size(); // listStr.put("#Tasks", String.valueOf(taskCnt)); addBuild("Processes...", listStr); } catch (Exception ex) { m_log.e("System-Processes %s", ex.getMessage()); } try { Map<String, String> listStr = new LinkedHashMap<String, String>(); listStr.put("LargeIconDensity", String.valueOf(actMgr.getLauncherLargeIconDensity())); listStr.put("LargeIconSize", String.valueOf(actMgr.getLauncherLargeIconSize())); putIf(listStr, "isRunningInTestHarness", "Yes", ActivityManager.isRunningInTestHarness()); putIf(listStr, "isUserAMonkey", "Yes", ActivityManager.isUserAMonkey()); addBuild("Misc...", listStr); } catch (Exception ex) { m_log.e("System-Misc %s", ex.getMessage()); } // --------------- Locale / Timezone ------------- try { Locale ourLocale = Locale.getDefault(); Date m_date = new Date(); TimeZone tz = TimeZone.getDefault(); Map<String, String> localeListStr = new LinkedHashMap<String, String>(); localeListStr.put("Locale Name", ourLocale.getDisplayName()); localeListStr.put(" Variant", ourLocale.getVariant()); localeListStr.put(" Country", ourLocale.getCountry()); localeListStr.put(" Country ISO", ourLocale.getISO3Country()); localeListStr.put(" Language", ourLocale.getLanguage()); localeListStr.put(" Language ISO", ourLocale.getISO3Language()); localeListStr.put(" Language Dsp", ourLocale.getDisplayLanguage()); localeListStr.put("TimeZoneID", tz.getID()); localeListStr.put(" DayLightSavings", tz.useDaylightTime() ? "Yes" : "No"); localeListStr.put(" In DLS", tz.inDaylightTime(m_date) ? "Yes" : "No"); localeListStr.put(" Short Name", tz.getDisplayName(false, TimeZone.SHORT, ourLocale)); localeListStr.put(" Long Name", tz.getDisplayName(false, TimeZone.LONG, ourLocale)); addBuild("Locale TZ...", localeListStr); } catch (Exception ex) { m_log.e("Locale/TZ %s", ex.getMessage()); } // --------------- Location Services ------------- try { Map<String, String> listStr = new LinkedHashMap<String, String>(); final LocationManager locMgr = (LocationManager) getActivity() .getSystemService(Context.LOCATION_SERVICE); GpsStatus gpsStatus = locMgr.getGpsStatus(null); if (gpsStatus != null) { listStr.put("Sec ToGetGPS", String.valueOf(gpsStatus.getTimeToFirstFix())); Iterable<GpsSatellite> satellites = gpsStatus.getSatellites(); Iterator<GpsSatellite> sat = satellites.iterator(); while (sat.hasNext()) { GpsSatellite satellite = sat.next(); putIf(listStr, String.format("Azm:%.0f, Elev:%.0f", satellite.getAzimuth(), satellite.getElevation()), String.format("%.2f Snr", satellite.getSnr()), satellite.usedInFix()); } } Location location = null; if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { location = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (null == location) location = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (null == location) location = locMgr.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); } if (null != location) { listStr.put(location.getProvider() + " lat,lng", String.format("%.3f, %.3f", location.getLatitude(), location.getLongitude())); } if (listStr.size() != 0) { List<String> gpsProviders = locMgr.getAllProviders(); int idx = 1; for (String providerName : gpsProviders) { LocationProvider provider = locMgr.getProvider(providerName); if (null != provider) { listStr.put(providerName, (locMgr.isProviderEnabled(providerName) ? "On " : "Off ") + String.format("Accuracy:%d Pwr:%d", provider.getAccuracy(), provider.getPowerRequirement())); } } addBuild("GPS...", listStr); } else addBuild("GPS", "Off"); } catch (Exception ex) { m_log.e(ex.getMessage()); } // --------------- Application Info ------------- ApplicationInfo appInfo = getActivity().getApplicationInfo(); if (null != appInfo) { Map<String, String> appList = new LinkedHashMap<String, String>(); try { appList.put("ProcName", appInfo.processName); appList.put("PkgName", appInfo.packageName); appList.put("DataDir", appInfo.dataDir); appList.put("SrcDir", appInfo.sourceDir); // appList.put("PkgResDir", getActivity().getPackageResourcePath()); // appList.put("PkgCodeDir", getActivity().getPackageCodePath()); String[] dbList = getActivity().databaseList(); if (dbList != null && dbList.length != 0) appList.put("DataBase", dbList[0]); // getActivity().getComponentName(). } catch (Exception ex) { } addBuild("AppInfo...", appList); } // --------------- Account Services ------------- final AccountManager accMgr = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE); if (null != accMgr) { Map<String, String> strList = new LinkedHashMap<String, String>(); try { for (Account account : accMgr.getAccounts()) { strList.put(account.name, account.type); } } catch (Exception ex) { m_log.e(ex.getMessage()); } addBuild("Accounts...", strList); } // --------------- Package Features ------------- PackageManager pm = getActivity().getPackageManager(); FeatureInfo[] features = pm.getSystemAvailableFeatures(); if (features != null) { Map<String, String> strList = new LinkedHashMap<String, String>(); for (FeatureInfo featureInfo : features) { strList.put(featureInfo.name, ""); } addBuild("Features...", strList); } // --------------- Sensor Services ------------- final SensorManager senMgr = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); if (null != senMgr) { Map<String, String> strList = new LinkedHashMap<String, String>(); // Sensor accelerometer = senMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // senMgr.registerListener(foo, accelerometer, SensorManager.SENSOR_DELAY_NORMAL); List<Sensor> listSensor = senMgr.getSensorList(Sensor.TYPE_ALL); try { for (Sensor sensor : listSensor) { strList.put(sensor.getName(), sensor.getVendor()); } } catch (Exception ex) { m_log.e(ex.getMessage()); } addBuild("Sensors...", strList); } try { if (Build.VERSION.SDK_INT >= 17) { final UserManager userMgr = (UserManager) getActivity().getSystemService(Context.USER_SERVICE); if (null != userMgr) { try { addBuild("UserName", userMgr.getUserName()); } catch (Exception ex) { m_log.e(ex.getMessage()); } } } } catch (Exception ex) { } try { Map<String, String> strList = new LinkedHashMap<String, String>(); int screenTimeout = Settings.System.getInt(getActivity().getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT); strList.put("ScreenTimeOut", String.valueOf(screenTimeout / 1000)); int rotate = Settings.System.getInt(getActivity().getContentResolver(), Settings.System.ACCELEROMETER_ROTATION); strList.put("RotateEnabled", String.valueOf(rotate)); if (Build.VERSION.SDK_INT >= 17) { // Global added in API 17 int adb = Settings.Global.getInt(getActivity().getContentResolver(), Settings.Global.ADB_ENABLED); strList.put("AdbEnabled", String.valueOf(adb)); } addBuild("Settings...", strList); } catch (Exception ex) { } if (expandAll) { // updateList(); int count = m_list.size(); for (int position = 0; position < count; position++) m_listView.expandGroup(position); } m_adapter.notifyDataSetChanged(); }
From source file:com.first.akashshrivastava.showernow.ShowerActivity.java
void setupStepcount() { /*mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); /*from w ww . j av a2 s. c o m*/ // have a default sensor configured //int sensorType = Sensor.TYPE_LIGHT; int sensorType = Sensor.TYPE_STEP_COUNTER; // we need the light sensor Sensor sensor = mSensorManager.getDefaultSensor(sensorType); // TODO we could have the sensor reading delay configurable also though that won't do much // in this use case since we work with the alarm manager mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL); */ mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); sensorType = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER); if (mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER) != null) { mSensorManager.registerListener(this, sensorType, SensorManager.SENSOR_DELAY_NORMAL); } else { Toast.makeText(getApplicationContext(), "Pedometer doesn't exist", Toast.LENGTH_SHORT).show(); } }
From source file:com.coincide.alphafitness.ui.Fragment_Main.java
@Override public void onPause() { super.onPause(); try {// w w w . j a va 2 s . c o m SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); sm.unregisterListener(this); } catch (Exception e) { e.printStackTrace(); } Database db = Database.getInstance(getActivity()); db.saveCurrentSteps(since_boot); db.close(); }
From source file:org.zywx.wbpalmstar.plugin.uexaudio.EUExAudio.java
@Override public boolean clean() { if (m_pfMusicPlayer != null) { m_pfMusicPlayer.stop();//ww w . j a v a 2 s . co m for (Integer id : IdsList) { m_pfMusicPlayer.stopSound(id); } IdsList.clear(); m_pfMusicPlayer = null; } if (sensorEventListener != null) { SensorManager mSensorManager = (SensorManager) mContext.getApplicationContext() .getSystemService(Context.SENSOR_SERVICE); mSensorManager.unregisterListener(sensorEventListener); sensorEventListener = null; } return true; }
From source file:com.davidmascharka.lips.TrackerActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //allow users to go back to Main Activity //TODO: test if this works on Marshmallow if (Build.VERSION.SDK_INT >= 23) { getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayShowHomeEnabled(true); } else {/*from w w w .jav a 2s. c om*/ getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestMyPermissions(); } setContentView(R.layout.activity_tracker); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction().add(R.id.container, new TrackerFragment()).commit(); } rotation = new float[9]; inclination = new float[9]; orientation = new float[3]; sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { updateLocation(location); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; loadXClassifierModels(); loadYClassifierModels(); loadPartitionClassifierModels(); setUpXInstances(); setUpYInstances(); setUpPartitionInstances(); wifiReadings = new LinkedHashMap<String, Integer>(); t = new Thread(); t.start(); //load5PartitionClassifiers = new Thread(); //load5PartitionClassifiers.start(); }
From source file:org.mozilla.gecko.GeckoAppShell.java
public static void enableSensor(int aSensortype) { SensorManager sm = (SensorManager) GeckoApp.mAppContext.getSystemService(Context.SENSOR_SERVICE); switch (aSensortype) { case SENSOR_PROXIMITY: if (gProximitySensor == null) gProximitySensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY); sm.registerListener(GeckoApp.mAppContext, gProximitySensor, SensorManager.SENSOR_DELAY_GAME); break;/*from w w w . j a va2s . c o m*/ } }
From source file:com.coincide.alphafitness.ui.Fragment_Main.java
@Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.action_split_count: Dialog_Split.getDialog(getActivity(), total_start + Math.max(todayOffset + since_boot, 0)).show(); return true; case R.id.action_pause: SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); Drawable d;/*from w ww .j a v a2 s .co m*/ if (getActivity().getSharedPreferences("pedometer", Context.MODE_PRIVATE).contains("pauseCount")) { // currently paused -> now resumed sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER), SensorManager.SENSOR_DELAY_UI, 0); item.setTitle(R.string.pause); d = getResources().getDrawable(R.drawable.ic_pause); } else { sm.unregisterListener(this); item.setTitle(R.string.resume); d = getResources().getDrawable(R.drawable.ic_resume); } d.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP); item.setIcon(d); getActivity().startService(new Intent(getActivity(), SensorListener.class).putExtra("action", SensorListener.ACTION_PAUSE)); return true; default: return ((Activity_Main) getActivity()).optionsItemSelected(item); } }
From source file:com.example.zoetablet.BasicFragmentActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Set the orientation //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); //Shapes and Coredx DDS Initialization // magic to enable WiFi multicast to work on some android platforms: WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); mcastLock = wifi.createMulticastLock("Tablet"); mcastLock.acquire();//from www. j a v a 2 s .c om //Tablet variables tablet = new Vector<TabletWriter>(); // open CoreDX DDS license file: BufferedReader br = null; String license = new String("<"); try { Log.i("Debug", "...Opening License"); br = new BufferedReader(new InputStreamReader(this.getAssets().open("coredx_dds.lic"))); } catch (IOException e) { Log.i("Debug", "...License did not open"); Log.e("Tablet", e.getMessage()); } if (br != null) { String ln; try { while ((ln = br.readLine()) != null) { license = new String(license + ln + "\n"); } } catch (IOException e) { // Log.e("Tablet", e.getMessage()); } } license = new String(license + ">"); Log.i("Tablet", "...License seems to be good"); //Initialize Variables XVel = 1; YVel = 2; CompassDir = 3; GPS_LN = 4; GPS_LT = 5; Log_DDS = DateFormat.getDateTimeInstance().format(new Date()); //For the Image, use current image display and String fileName = "/storage/sdcard0/DCIM/no_video.jpg"; Bitmap bmp; bmp = BitmapFactory.decodeFile(fileName); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, 40, baos); buffer = baos.toByteArray(); data_image_DDS = buffer; Log.i("Tablet", "Creating Subscriber"); class TestDataReaderListener implements DataReaderListener { @Override public long get_nil_mask() { return 0; } @Override public void on_requested_deadline_missed(DataReader dr, RequestedDeadlineMissedStatus status) { System.out.println(" @@@@@@@@@@@ REQUESTED DEADLINE MISSED @@@@@"); System.out.println(" @@@@@@@@@@@ @@@@@"); System.out.println(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); }; @Override public void on_requested_incompatible_qos(DataReader dr, RequestedIncompatibleQosStatus status) { System.out.println(" @@@@@@@@@@@ REQUESTED INCOMPAT QOS @@@@@@@@"); System.out.println(" @@@@@@@@@@@ dr = " + dr); System.out.println(" @@@@@@@@@@@ @@@@@@@@"); System.out.println(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); }; @Override public void on_sample_rejected(DataReader dr, SampleRejectedStatus status) { }; @Override public void on_liveliness_changed(DataReader dr, LivelinessChangedStatus status) { TopicDescription td = dr.get_topicdescription(); System.out.println(" @@@@@@@@@@@ LIVELINESS CHANGED " + td.get_name() + " @@@@@@@@@@"); } @Override public void on_subscription_matched(DataReader dr, SubscriptionMatchedStatus status) { TopicDescription td = dr.get_topicdescription(); System.out.println(" @@@@@@@@@@@ SUBSCRIPTION MATCHED @@@@@@@@@@"); System.out.println( " @@@@@@@@@@@ topic = " + td.get_name() + " (type: " + td.get_type_name() + ")"); System.out.println(" @@@@@@@@@@@ current = " + status.get_current_count()); System.out.println(" @@@@@@@@@@@ @@@@@@@@@@"); System.out.println(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); } @Override public void on_sample_lost(DataReader dr, SampleLostStatus status) { System.out.println(" @@@@@@@@@@@ SAMPLE LOST @@@@@@@@@@"); }; @Override public void on_data_available(DataReader dr) { TopicDescription td = dr.get_topicdescription(); dataDDSDataReader data_message = (dataDDSDataReader) dr; System.out.println(" @@@@@@@@@@@ DATA AVAILABLE @@@@@@@@@@"); System.out.println( " @@@@@@@@@@@ topic = " + td.get_name() + " (type: " + td.get_type_name() + ")"); samples = new dataDDSSeq(); SampleInfoSeq si = new SampleInfoSeq(); ReturnCode_t retval = data_message.take(samples, si, 100, coredxConstants.DDS_ANY_SAMPLE_STATE, coredxConstants.DDS_ANY_VIEW_STATE, coredxConstants.DDS_ANY_INSTANCE_STATE); System.out.println(" @@@@@@@@@@@ DR.read() ===> " + retval); if (retval == ReturnCode_t.RETCODE_OK) { if (samples.value == null) System.out.println(" @@@@@@@@@@@ samples.value = null"); else { System.out.println(" @@@@@@@@@@@ samples.value.length= " + samples.value.length); for (int i = 0; i < samples.value.length; i++) { System.out.println(" State : " + (si.value[i].instance_state == coredxConstants.DDS_ALIVE_INSTANCE_STATE ? "ALIVE" : "NOT ALIVE")); System.out.println(" TimeStamp : " + si.value[i].source_timestamp.sec + "." + si.value[i].source_timestamp.nanosec); System.out.println(" Handle : " + si.value[i].instance_handle.value); System.out.println(" WriterHandle: " + si.value[i].publication_handle.value); System.out.println(" SampleRank : " + si.value[i].sample_rank); if (si.value[i].valid_data) System.out.println(" XVel: " + samples.value[i].XVel_DDS); System.out.println(" YVel: " + samples.value[i].YVel_DDS); System.out.println(" CompassDir: " + samples.value[i].CompassDir_DDS); System.out.println(" GPS_LT: " + samples.value[i].GPS_LT_DDS); System.out.println(" GPS_LN: " + samples.value[i].GPS_LN_DDS); System.out.println(" Log_DDS: " + samples.value[i].Log_DDS); //Capture data values for display BasicFragmentActivity.XVel = samples.value[i].XVel_DDS; BasicFragmentActivity.YVel = samples.value[i].YVel_DDS; BasicFragmentActivity.CompassDir = samples.value[i].CompassDir_DDS; BasicFragmentActivity.GPS_LT = samples.value[i].GPS_LT_DDS; BasicFragmentActivity.GPS_LN = samples.value[i].GPS_LN_DDS; BasicFragmentActivity.Log_DDS = samples.value[i].Log_DDS; BasicFragmentActivity.data_image_DDS = samples.value[i].data_image_DDS; } } data_message.return_loan(samples, si); } else { } System.out.println(" @@@@@@@@@@@ @@@@@@@@@@"); System.out.println(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); }; } ; System.out.println("STARTING -------------------------"); DomainParticipantFactory dpf = DomainParticipantFactory.get_instance(); dpf.set_license(license); dpf.get_default_participant_qos(dp_qos_tablet); DomainParticipant dp = null; System.out.println("CREATE PARTICIPANT ---------------"); dp = dpf.create_participant(0, /* domain Id */ dp_qos_tablet, //null, /* default qos */ null, /* no listener */ 0); if (dp == null) { //failed to create DomainParticipant -- bad license android.util.Log.e("CoreDX DDS", "Unable to create Tablet DomainParticipant."); } SubscriberQos sub_qos_tablet = new SubscriberQos(); Log.i("Tablet", "creating publisher/subscriber"); sub_tablet = dp.create_subscriber(sub_qos_tablet, null, 0); System.out.println("REGISTERING TYPE -----------------"); dataDDSTypeSupport ts = new dataDDSTypeSupport(); ReturnCode_t returnValue = ts.register_type(dp, null); if (returnValue != ReturnCode_t.RETCODE_OK) { System.out.println("ERROR registering type\n"); return; } System.out.println("CREATE TOPIC ---------------------"); /* create a DDS Topic with the FilterMsg data type. */ Topic topics = dp.create_topic("dataDDS", ts.get_type_name(), DDS.TOPIC_QOS_DEFAULT, null, 0); if (topics == null) { System.out.println("Error creating topic"); return; } System.out.println("CREATE SUBSCRIBER ----------------"); SubscriberQos sub_qos = null; SubscriberListener sub_listener = null; Subscriber sub = dp.create_subscriber(sub_qos, sub_listener, 0); System.out.println("READER VARIABLES ----------------"); DataReaderQos dr_qos = new DataReaderQos(); sub.get_default_datareader_qos(dr_qos); dr_qos.entity_name.value = "JAVA_DR"; dr_qos.history.depth = 10; DataReaderListener dr_listener = new TestDataReaderListener(); System.out.println("CREATE DATAREADER ----------------"); //Create DDS Data reader dataDDSDataReader dr = (dataDDSDataReader) sub.create_datareader(topics, DDS.DATAREADER_QOS_DEFAULT, dr_listener, DDS.DATA_AVAILABLE_STATUS); System.out.println("DATAREADER CREATED ----------------"); //Cheack to see if DDS Data Reader worked if (dr == null) { System.out.println("ERROR creating data reader\n"); //return; } // We default to building our Fragment at runtime, but you can switch the layout here // to R.layout.activity_fragment_xml in order to have the Fragment added during the // Activity's layout inflation. setContentView(R.layout.holygrail); Log.i("Tablet", "called set content view"); FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.findFragmentById(R.id.center_pane_top); // You can find Fragments just like you would with a // View by using FragmentManager. Log.i("Tablet", "...declare fragment"); // If wLog.ie are using activity_fragment_xml.xml then this the fragment will not be // null, otherwise it will be. if (fragment == null) { //Image View Fragment Log.i("Debug", "...calling fragment center pane"); FragmentTransaction ft = fm.beginTransaction(); ft.add(R.id.center_pane_top, new BasicFragment()); ft.addToBackStack(null); //Logging Fragment Log.i("Debug", "...calling fragment left pane top"); //ft.add(R.id.left_pane_top, new LoggingFragment()); ft.add(R.id.left_pane_top, new LoggingFragment()); ft.addToBackStack(null); //Connecting Fragment Log.i("Debug", "...calling fragment left pane bottom"); //ft.add(R.id.left_pane_bottom,new ControllerFragment()); ft.add(R.id.left_pane_bottom, new ConnectionFragment()); ft.addToBackStack(null); //Compass Fragment Log.i("Debug", "...calling fragment right pane top"); //ft.add(R.id.right_pane_top,new BasicFragment2()); ft.add(R.id.right_pane_top, new BasicFragment2()); ft.addToBackStack(null); //Navigation Fragment Log.i("Debug", "...calling fragment right pane bottom"); //ft.add(R.id.center_pane_bottom,new NavigationFragment()); ft.add(R.id.center_pane_bottom, new DualJoystickActivity()); ft.addToBackStack(null); //Datalog Fragment Log.i("Debug", "...calling fragment middle pane bottom"); //ft.add(R.id.right_pane_bottom,new DatalogFragment()); ft.add(R.id.right_pane_bottom, new DatalogFragment()); ft.addToBackStack(null); //Commit the fragment or it will not be added Log.i("Debug", "...comitting"); ft.commit(); } //Joystick variables txtX1 = (TextView) this.findViewById(R.id.TextViewX1); txtY1 = (TextView) this.findViewById(R.id.TextViewY1); txtX2 = (TextView) this.findViewById(R.id.TextViewX2); txtY2 = (TextView) this.findViewById(R.id.TextViewY2); joystick = (DualJoystickView) this.findViewById(R.id.dualjoystickView); JoystickMovedListener _listenerLeft = new JoystickMovedListener() { @Override public void OnMoved(int pan, int tilt) { txtX1.setText(Integer.toString(pan)); txtY1.setText(Integer.toString(tilt)); } @Override public void OnReleased() { txtX1.setText("released"); txtY1.setText("released"); } @Override public void OnReturnedToCenter() { txtX1.setText("stopped"); txtY1.setText("stopped"); }; }; JoystickMovedListener _listenerRight = new JoystickMovedListener() { @Override public void OnMoved(int pan, int tilt) { txtX2.setText(Integer.toString(pan)); txtY2.setText(Integer.toString(tilt)); } @Override public void OnReleased() { txtX2.setText("released"); txtY2.setText("released"); } @Override public void OnReturnedToCenter() { txtX2.setText("stopped"); txtY2.setText("stopped"); }; }; joystick.setOnJostickMovedListener(_listenerLeft, _listenerRight); //Compass Activities compassView = (CompassView) this.findViewById(R.id.compassView); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); // updateOrientation(new float[] {0, 0, 0}); // updateOrientation(calculateOrientation()); // Hook up button presses to the appropriate event handler. // Quit Button -- not really necessary: The 'Back' button does // the same thing, but we create this just for fun.. ((Button) findViewById(R.id.quitButton)).setOnClickListener(mQuitListener); tv_myAddr = (TextView) findViewById(R.id.myAddress); if (tv_myAddr != null) tv_myAddr.setText("<detecting>"); mHandler.postDelayed(mUpdateMyAddress, 1000); // every 10 sec */ //Updating Datalog fragment view tv_XVel = (TextView) findViewById(R.id.XVel); if (tv_XVel != null) tv_XVel.setText("<detecting>"); tv_YVel = (TextView) findViewById(R.id.YVel); if (tv_YVel != null) tv_YVel.setText("<detecting>"); tv_CompassDir = (TextView) findViewById(R.id.CompassDir); if (tv_CompassDir != null) tv_CompassDir.setText("<detecting>"); tv_GPSLocation = (TextView) findViewById(R.id.GPSLocation); if (tv_GPSLocation != null) tv_GPSLocation.setText("<detecting>"); tv_Log_DDS = (TextView) findViewById(R.id.loggingMessage); if (tv_Log_DDS != null) tv_Log_DDS.setText("<detecting>"); mHandler.postDelayed(mUpdateDatalog, 500); // every 1 sec */ }