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.sitewhere.android.example.ExampleFragment.java
/** * Only schedule SiteWhere reporting thread once we have a connection to the server. *///from w ww . jav a2s . co m public void startDeviceMonitoring() { Log.d(TAG, "Starting device monitoring."); getActivity().runOnUiThread(new Runnable() { @Override public void run() { // Start location updates. boolean locationStarted = false; locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "No permissions for location. Requesting permissions from user."); requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }, LOCATION_REQUEST_CODE); return; } if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ExampleFragment.this); locationStarted = true; Log.d(TAG, "Started monitoring locations via GPS provider."); } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ExampleFragment.this); locationStarted = true; Log.d(TAG, "Started monitoring locations via network provider."); } else { locationStarted = false; Log.d(TAG, "No location provider available. Will not monitor location."); } // Start accelerometer updates. boolean accelerometerStarted = false; sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) { rotationVector = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); sensorManager.registerListener(ExampleFragment.this, rotationVector, SensorManager.SENSOR_DELAY_NORMAL); accelerometerStarted = true; Log.d(TAG, "Started monitoring accelerometer."); } else { Toast.makeText(getActivity().getApplicationContext(), "Unable to start accelerometer updates. No accelerometer provided", Toast.LENGTH_LONG); accelerometerStarted = false; Log.d(TAG, "Unable to monitor accelerometer."); } // Send alerts to SiteWhere. SiteWhereMessageClient messageClient = SiteWhereMessageClient.getInstance(); try { if (locationStarted) messageClient.sendDeviceAlert(messageClient.getUniqueDeviceId(), "location.started", "Started to read location data.", null); } catch (SiteWhereMessagingException ex) { Log.e(TAG, "Unable to send location.started alert to SiteWhere."); } try { if (accelerometerStarted) messageClient.sendDeviceAlert(messageClient.getUniqueDeviceId(), "accelerometer.started", "Started to read accelerometer data.", null); } catch (SiteWhereMessagingException e) { Log.e(TAG, "Unable to send accelerometer.started alert to SiteWhere."); } if (scheduler != null) { scheduler.shutdownNow(); } scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new SiteWhereDataReporter(), SEND_INTERVAL_IN_SECONDS, SEND_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); Log.d(TAG, "Set up scheduler for monitoring."); } }); }
From source file:com.android.camera2.its.ItsService.java
@Override public void onCreate() { try {/*from w ww. java 2 s .co m*/ mThreadExitFlag = false; // Get handle to camera manager. mCameraManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE); if (mCameraManager == null) { throw new ItsException("Failed to connect to camera manager"); } mBlockingCameraManager = new BlockingCameraManager(mCameraManager); mCameraListener = new BlockingStateCallback(); // Register for motion events. mEvents = new LinkedList<MySensorEvent>(); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAccelSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mMagSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); mSensorManager.registerListener(this, mAccelSensor, SensorManager.SENSOR_DELAY_FASTEST); mSensorManager.registerListener(this, mMagSensor, SensorManager.SENSOR_DELAY_FASTEST); mSensorManager.registerListener(this, mGyroSensor, SensorManager.SENSOR_DELAY_FASTEST); // Get a handle to the system vibrator. mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // Create threads to receive images and save them. for (int i = 0; i < MAX_NUM_OUTPUT_SURFACES; i++) { mSaveThreads[i] = new HandlerThread("SaveThread" + i); mSaveThreads[i].start(); mSaveHandlers[i] = new Handler(mSaveThreads[i].getLooper()); } // Create a thread to handle object serialization. (new Thread(new SerializerRunnable())).start(); ; // Create a thread to receive capture results and process them. mResultThread = new HandlerThread("ResultThread"); mResultThread.start(); mResultHandler = new Handler(mResultThread.getLooper()); // Create a thread for the camera device. mCameraThread = new HandlerThread("ItsCameraThread"); mCameraThread.start(); mCameraHandler = new Handler(mCameraThread.getLooper()); // Create a thread to process commands, listening on a TCP socket. mSocketRunnableObj = new SocketRunnable(); (new Thread(mSocketRunnableObj)).start(); } catch (ItsException e) { Logt.e(TAG, "Service failed to start: ", e); } }
From source file:au.gov.ga.worldwind.androidremote.client.Remote.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Normally one shouldn't instantiate all these objects in the onCreate method, //as onCreate is called every time a configuration change occurs (orientation, //keyboard hidden, screen size, etc). But we are handling configuration changes //ourselves.//from w w w. j a va2 s . com //hide the status bar this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //get local Bluetooth adapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { Toast.makeText(this, R.string.bluetooth_unavailable, Toast.LENGTH_LONG).show(); finish(); return; } communicator = new AndroidCommunicator(this, bluetoothAdapter); communicator.addListener(this); remoteViewCommunicator = new SocketAndroidCommunicator(this); DatasetModelState datasetsState = new DatasetModelState(communicator, this); LayerModelState layersState = new LayerModelState(communicator, this); PlaceModelState placesState = new PlaceModelState(communicator, this); ItemModelState[] states = new ItemModelState[] { datasetsState, layersState, placesState }; for (ItemModelState state : states) { itemModelStates.put(state.getModel().getId(), state); ItemModelFragmentMenuProvider menuProvider = new EmptyMenuProvider(); if (state == placesState) { menuProvider = new PlacesMenuProvider(communicator); } menuProviders.put(state.getModel().getId(), menuProvider); } controlFragment = ControlFragment.newInstance(remoteViewCommunicator); datasetsFragment = ItemModelFragment.newInstance(datasetsState.getModel().getId(), false); layersFragment = ItemModelFragment.newInstance(layersState.getModel().getId(), false); flatLayersFragment = ItemModelFragment.newInstance(layersState.getModel().getId(), true); placesFragment = ItemModelFragment.newInstance(placesState.getModel().getId(), false); tabFragments = new Fragment[] { controlFragment, datasetsFragment, layersFragment, flatLayersFragment, placesFragment }; //create the tabs getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); int[] tabIds = new int[] { R.string.controls_tab, R.string.datasets_tab, R.string.layers_tab, R.string.flat_layers_tab, R.string.places_tab }; for (int i = 0; i < tabIds.length; i++) { ActionBar.Tab tab = getSupportActionBar().newTab(); tab.setTag(tabIds[i]); tab.setText(tabIds[i]); tab.setTabListener(this); getSupportActionBar().addTab(tab); } getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setHomeButtonEnabled(true); //setup the shake sensor sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); sensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() { @Override public void onShake() { communicator.sendMessage(new ShakeMessage()); } }); // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Define a listener that responds to location updates LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { if (isSendLocation()) { communicator.sendMessage(new LocationMessage(location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getAccuracy(), location.getBearing())); } } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); }
From source file:galilei.kelimekavanozu.activity.ThemeChooserActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Accelerometer check PackageManager manager = getPackageManager(); hasAccelerometer = manager.hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER); setContentView(R.layout.activity_theme_chooser); SugarContext.init(this); arkaplan500 = (ImageView) findViewById(R.id.arkaplan500); kavanoz = (ImageView) findViewById(R.id.cannonball_logo); recyclerView = (RecyclerView) findViewById(R.id.main_list); final Animation shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake); fab = (FloatingActionButton) findViewById(R.id.fab); StaggeredGridLayoutManager gridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); gridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS); recyclerView.setLayoutManager(gridLayoutManager); initialCount = Note.count(Note.class); if (savedInstanceState != null) modifyPos = savedInstanceState.getInt("modify"); if (initialCount >= 0) { notes = Note.listAll(Note.class); adapter = new KelimelerAdapter(ThemeChooserActivity.this, notes); recyclerView.setAdapter(adapter); }// ww w . ja v a 2 s.c om if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Drawable drawable = ContextCompat.getDrawable(this, R.drawable.ic_add_24dp); drawable = DrawableCompat.wrap(drawable); DrawableCompat.setTint(drawable, Color.WHITE); DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_IN); fab.setImageDrawable(drawable); } fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Crashlytics.log("Yeni Kelime: butona basld"); // Answers.getInstance().logCustom(new CustomEvent("Ekle butonuna basld")); Intent i = new Intent(ThemeChooserActivity.this, AddNoteActivity.class); startActivity(i); } }); if (isNetworkConnected()) { new arkaplan().execute(); } // Handling swipe to delete setUpViews(); ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { //Remove swiped item from list and notify the RecyclerView final int position = viewHolder.getAdapterPosition(); final Note note = notes.get(viewHolder.getAdapterPosition()); notes.remove(viewHolder.getAdapterPosition()); adapter.notifyItemRemoved(position); note.delete(); initialCount -= 1; Snackbar.make(fab, "Kelime silindi", Snackbar.LENGTH_SHORT) .setAction("GER AL", new View.OnClickListener() { @Override public void onClick(View v) { note.save(); notes.add(position, note); adapter.notifyItemInserted(position); initialCount += 1; } }).show(); } }; ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback); itemTouchHelper.attachToRecyclerView(recyclerView); adapter.SetOnItemClickListener(new KelimelerAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Log.d("Main", "click"); Intent i = new Intent(ThemeChooserActivity.this, AddNoteActivity.class); i.putExtra("isEditing", true); i.putExtra("note_title", notes.get(position).title); i.putExtra("note", notes.get(position).note); i.putExtra("note_time", notes.get(position).time); modifyPos = position; startActivity(i); } }); if (hasAccelerometer) { kavanoz.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // View element to be shaken // Perform animation if (notclick) { kavanoz.startAnimation(shake); shakemode = true; notclick = false; Snackbar.make(fab, "Rastgele kelimelerden birini grmek iin telefonunuzu sallayn.", Snackbar.LENGTH_LONG).show(); kavanoz.setColorFilter(Color.argb(100, 255, 140, 0)); } else { shakemode = false; notclick = true; kavanoz.setColorFilter(getResources().getColor(R.color.green)); } } }); // ShakeDetector initialization mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mShakeDetector = new ShakeDetector(); mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() { @Override public void onShake(int count) { if (shakemode) { /* * The following method, "handleShakeEvent(count):" is a stub // * method you would use to setup whatever you want done once the * device has been shook. */ // View element to be shaken // Perform animation Crashlytics.log("Shake event : triggered"); Answers.getInstance().logCustom(new CustomEvent("Shake event : tetiklendi")); kavanoz.startAnimation(shake); new rastgeletweet().execute(); } } }); } }
From source file:com.acrr.acdisplay.services.activemode.ActiveModeService.java
@Override public void onStart(Object... objects) { if (DEBUG)//from w ww .j a v a 2 s. c o m Log.d(TAG, "Starting listening to sensors."); Context context = getContext(); SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); for (ActiveModeSensor sensor : mSensors) { sensor.registerCallback(this); sensor.onAttached(sensorManager, context); } mActiveChargingEnabled = Config.getInstance().isActiveModeActiveChargingEnabled(); if (mActiveChargingEnabled) { mPluggedAtomic.react(PowerUtils.isPlugged(context)); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); context.registerReceiver(mReceiver, intentFilter); } }
From source file:net.line2soft.preambul.views.SlippyMapActivity.java
@Override public void onPause() { //Unregister compass listener CompassView cpv = (CompassView) findViewById(R.id.compass); CompassView cpvBig = (CompassView) findViewById(R.id.compassBig); if (cpv.getVisibility() == View.VISIBLE || cpvBig.getVisibility() == View.VISIBLE) { SensorManager mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mySensorManager.unregisterListener(listener); }//w ww .j a v a 2 s . co m //Disable map MapView mv = (MapView) findViewById(R.id.mapView); mv.setEnabled(false); displayExcursion(-1); overlayPoiItemMarker.clear(); //Delete value of SET_COORDINATES getIntent().removeExtra(MAP_SET_COORDINATES); super.onPause(); }
From source file:com.kircherelectronics.accelerationfilter.activity.AccelerationPlotActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.plot_sensor_activity); // Read in the saved prefs readPrefs();//ww w.j a v a2 s. c o m initTextOutputs(); initIcons(); initStatistics(); initFilters(); initColor(); initPlots(); sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE); handler = new Handler(); runnable = new Runnable() { @Override public void run() { handler.postDelayed(this, 100); plotData(); updateAccelerationText(); } }; }
From source file:ro.ciubex.keepscreenlock.MainApplication.java
/** * Called when the application is starting, before any activity, service, * or receiver objects (excluding content providers) have been created. *///from w w w. ja va 2s.c o m @Override public void onCreate() { super.onCreate(); MainApplication.isEmulator = String.valueOf(Build.PRODUCT).startsWith("sdk"); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mDeviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); mComponentName = new ComponentName(this, AdminPermissionReceiver.class); mSdkInt = android.os.Build.VERSION.SDK_INT; mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); initLocale(); checkKeepScreenLockReceiver(); }
From source file:com.richwareham.android.logallthethings.Camera2VideoFragment.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this) .addApi(LocationServices.API).build(); mLocationRequest = new LocationRequest(); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setInterval(5000);/*from w w w . j av a2s.c o m*/ mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); int sensor_types[] = { Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_GYROSCOPE, Sensor.TYPE_MAGNETIC_FIELD, }; mSensors = new ArrayList<Sensor>(); for (int type : sensor_types) { Sensor s = mSensorManager.getDefaultSensor(type); if (s == null) { continue; } mSensors.add(s); } }
From source file:com.coincide.alphafitness.ui.Fragment_Main.java
@Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { // final View v = inflater.inflate(R.layout.fragment_overview, null); View v = null;/*from w ww .j a v a 2 s . com*/ v = inflater.inflate(R.layout.fragment_main, container, false); // stepsView = (TextView) v.findViewById(R.id.steps); // totalView = (TextView) v.findViewById(R.id.total); totalView = (TextView) v.findViewById(R.id.tv_distance); tv_avg = (TextView) v.findViewById(R.id.tv_avg); tv_max = (TextView) v.findViewById(R.id.tv_max); tv_min = (TextView) v.findViewById(R.id.tv_min); // averageView = (TextView) v.findViewById(R.id.average); /* pg = (PieChart) v.findViewById(R.id.graph); // slice for the steps taken today sliceCurrent = new PieModel("", 0, Color.parseColor("#99CC00")); pg.addPieSlice(sliceCurrent); // slice for the "missing" steps until reaching the goal sliceGoal = new PieModel("", Fragment_Settings.DEFAULT_GOAL, Color.parseColor("#CC0000")); pg.addPieSlice(sliceGoal); pg.setOnClickListener(new OnClickListener() { @Override public void onClick(final View view) { showSteps = !showSteps; stepsDistanceChanged(); } }); pg.setDrawValueInPie(false); pg.setUsePieRotation(true); pg.startAnimation(); */ /* * MainActivity * */ // Always cast your custom Toolbar here, and set it as the ActionBar. Toolbar tb = (Toolbar) v.findViewById(R.id.toolbar); ((AppCompatActivity) getActivity()).setSupportActionBar(tb); TextView tv_tb_center = (TextView) tb.findViewById(R.id.tv_tb_center); tv_tb_center.setText("ALPHA FITNESS"); /* ImageButton imgbtn_cart = (ImageButton) tb.findViewById(R.id.imgbtn_cart); imgbtn_cart.setVisibility(View.GONE);*/ tb.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().onBackPressed(); } }); // Get the ActionBar here to configure the way it behaves. final ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar(); //ab.setHomeAsUpIndicator(R.drawable.ic_menu); // set a custom icon for the default home button ab.setDisplayShowHomeEnabled(false); // show or hide the default home button ab.setDisplayHomeAsUpEnabled(false); ab.setDisplayShowCustomEnabled(false); // enable overriding the default toolbar layout ab.setDisplayShowTitleEnabled(false); // disable the default title element here (for centered title) tv_duration = (TextView) v.findViewById(R.id.tv_duration); startButton = (Button) v.findViewById(R.id.btn_start); if (isButtonStartPressed) { startButton.setBackgroundResource(R.drawable.btn_stop_states); startButton.setText(R.string.btn_stop); try { SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER), SensorManager.SENSOR_DELAY_UI, 0); } catch (Exception e) { e.printStackTrace(); } } else { try { SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); sm.unregisterListener(this); } catch (Exception e) { e.printStackTrace(); } } startButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { onSWatchStart(); } }); iv_profile = (ImageView) v.findViewById(R.id.iv_profile); iv_profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Database db = Database.getInstance(getActivity()); tot_workouts = db.getTotWorkouts(); tot_workTime = db.getWorkTime(); Log.e("Tot Work time", tot_workTime + ""); // int seconds = (int) (tot_workTime / 1000) % 60; // int minutes = (int) ((tot_workTime / (1000 * 60)) % 60); long millis = tot_workTime * 100; // obtained from StopWatch long hours = (millis / 1000) / 3600; long minutes = (millis / 1000) / 60; long seconds = (millis / 1000) % 60; db.close(); Intent i = new Intent(getActivity(), ProfileActivity.class); i.putExtra("avg_distance", avg_distance + ""); i.putExtra("all_distance", all_distance + ""); i.putExtra("avg_time", tv_duration.getText().toString()); i.putExtra("all_time", tv_duration.getText().toString()); i.putExtra("avg_calories", avg_calories + ""); i.putExtra("all_calories", all_calories + ""); i.putExtra("tot_workouts", tot_workouts + ""); i.putExtra("avg_workouts", tot_workouts + ""); i.putExtra("tot_workTime", hours + " hrs " + minutes + " min " + seconds + " sec"); startActivity(i); } }); // Getting Google Play availability status int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext()); if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available int requestCode = 10; Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode); dialog.show(); } else { // Google Play Services are available // Initializing mMarkerPoints = new ArrayList<LatLng>(); // Getting reference to SupportMapFragment of the activity_main // SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map); MapFragment fm = (MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.map); // Getting Map for the SupportMapFragment mGoogleMap = fm.getMap(); // Enable MyLocation Button in the Map mGoogleMap.setMyLocationEnabled(true); // Getting LocationManager object from System Service LOCATION_SERVICE LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE); // Creating a criteria object to retrieve provider Criteria criteria = new Criteria(); // Getting the name of the best provider String provider = locationManager.getBestProvider(criteria, true); // Getting Current Location From GPS Location location; if (provider != null) { if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return null; } location = locationManager.getLastKnownLocation(provider); locationManager.requestLocationUpdates(provider, 20000, 0, this); } else { location = new Location(""); location.setLatitude(0.0d);//your coords of course location.setLongitude(0.0d); } if (location != null) { onLocationChanged(location); } // Setting onclick event listener for the map mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng point) { // Already map contain destination location if (mMarkerPoints.size() > 1) { FragmentManager fm = getActivity().getSupportFragmentManager(); mMarkerPoints.clear(); mGoogleMap.clear(); LatLng startPoint = new LatLng(mLatitude, mLongitude); drawMarker(startPoint); } drawMarker(point); // Checks, whether start and end locations are captured if (mMarkerPoints.size() >= 2) { LatLng origin = mMarkerPoints.get(0); LatLng dest = mMarkerPoints.get(1); // Getting URL to the Google Directions API String url = getDirectionsUrl(origin, dest); DownloadTask downloadTask = new DownloadTask(); // Start downloading json data from Google Directions API downloadTask.execute(url); } } }); fixedCentreoption = new MarkerOptions(); mGoogleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition position) { // TODO Auto-generated method stub // Get the center of the Map. mGoogleMap.clear(); LatLng centerOfMap = mGoogleMap.getCameraPosition().target; // Update your Marker's position to the center of the Map. fixedCentreoption.position(centerOfMap); // mGoogleMap.addMarker(fixedCentreoption); // drawMarker(centerOfMap); LatLng origin = new LatLng(0.0d, 0.0d); ; if (mMarkerPoints.size() > 0) { origin = mMarkerPoints.get(0); } // LatLng dest = mMarkerPoints.get(1); LatLng dest = centerOfMap; // Getting URL to the Google Directions API String url = getDirectionsUrl(origin, dest); DownloadTask downloadTask = new DownloadTask(); // Start downloading json data from Google Directions API downloadTask.execute(url); GPSTracker gpsTracker = new GPSTracker(getActivity().getApplicationContext()); // String Addrs = gpsTracker.location(); Addrs = gpsTracker.locationBasedOnLatlng(centerOfMap); // Toast.makeText(getApplicationContext(), Addrs, Toast.LENGTH_LONG).show(); } }); } SharedPreferences sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); mBodyWeight = Float.parseFloat(sharedpreferences.getString(sp_weight, "50")); return v; }