Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 25.70 KB | None | 0 0
  1. public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
  2. GoogleApiClient.OnConnectionFailedListener, LocationListener {
  3.  
  4. private GoogleMap mMap;
  5. String Longitude, Latitude;
  6. Location ll;
  7. final String TAG = "GPS";
  8. private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
  9. private long FASTEST_INTERVAL = 2000; /* 2 sec */
  10. static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
  11. GoogleApiClient gac;
  12. LocationRequest locationRequest;
  13.  
  14.  
  15. int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;
  16. PlaceAutocompleteFragment autocompleteFragment;
  17. Marker markerDesti, markerCurrentLoc;
  18. LatLng DestiLoc;
  19. double LatDesti, latCurrent;
  20. double LonDesti, lngCurrent;
  21.  
  22. private static final int REQUEST_CODE_PERMISSION = 2;
  23. String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;
  24. PendingIntent mGeofencePendingIntent;
  25. ArrayList<Geofence> mGeofenceList;
  26. private GeofencingClient mGeofencingClient;
  27.  
  28. TextView TestBtn;
  29.  
  30. LocationRequest mLocationRequest;
  31.  
  32. private GeofancingResultCallBack geofancingResultCallBack;
  33.  
  34.  
  35. public static final class Constants {
  36. public static int GEOFENCE_RADIUS_IN_METERS = 1000;
  37. public static int GEOFENCE_EXPIRATION_IN_MILLISECONDS = 1000;
  38. }
  39.  
  40. @Override
  41. protected void onCreate(Bundle savedInstanceState) {
  42. super.onCreate(savedInstanceState);
  43. setContentView(R.layout.activity_main);
  44.  
  45. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
  46. .findFragmentById(R.id.map);
  47. mapFragment.getMapAsync(this);
  48.  
  49. TestBtn = (TextView) findViewById(R.id.TestBtn);
  50.  
  51. isGooglePlayServicesAvailable();
  52. if (!isLocationEnabled())
  53. showAlert();
  54.  
  55. locationRequest = new LocationRequest();
  56. locationRequest.setInterval(UPDATE_INTERVAL);
  57. locationRequest.setFastestInterval(FASTEST_INTERVAL);
  58. locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  59.  
  60. gac = new GoogleApiClient.Builder(this)
  61. .addConnectionCallbacks(this)
  62. .addOnConnectionFailedListener(this)
  63. .addApi(LocationServices.API)
  64. .build();
  65.  
  66.  
  67. //========================= PLACES API DROP DOWN============================//
  68.  
  69.  
  70. mGeofencingClient = LocationServices.getGeofencingClient(this);
  71. mGeofenceList = new ArrayList<>();
  72.  
  73.  
  74. }
  75.  
  76. @Override
  77. public void onMapReady(GoogleMap googleMap) {
  78.  
  79. mMap = googleMap;
  80.  
  81.  
  82. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  83. != PackageManager.PERMISSION_GRANTED &&
  84. ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
  85. != PackageManager.PERMISSION_GRANTED) {
  86. // TODO: Consider calling
  87. // ActivityCompat#requestPermissions
  88. // here to request the missing permissions, and then overriding
  89. // public void onRequestPermissionsResult(int requestCode, String[] permissions,
  90. // int[] grantResults)
  91. // to handle the case where the user grants the permission. See the documentation
  92. // for ActivityCompat#requestPermissions for more details.
  93. return;
  94. }
  95. mMap.setMyLocationEnabled(true);
  96.  
  97. getPlacesApi();
  98. }
  99.  
  100. @Override
  101. protected void onStart() {
  102. gac.connect();
  103. super.onStart();
  104. }
  105.  
  106. @Override
  107. protected void onStop() {
  108. gac.disconnect();
  109. super.onStop();
  110. }
  111.  
  112. @Override
  113. public void onLocationChanged(Location location) {
  114. if (location != null) {
  115. updateUI(location);
  116.  
  117. }
  118. }
  119.  
  120. @Override
  121. public void onConnected(@Nullable Bundle bundle) {
  122. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  123. != PackageManager.PERMISSION_GRANTED
  124. && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
  125. != PackageManager.PERMISSION_GRANTED) {
  126. ActivityCompat.requestPermissions(MapsActivity.this,
  127. new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
  128. MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
  129.  
  130. return;
  131. }
  132. Log.d(TAG, "onConnected");
  133.  
  134. ll = LocationServices.FusedLocationApi.getLastLocation(gac);
  135. Log.d(TAG, "LastLocation: " + (ll == null ? "NO LastLocation" : ll.toString()));
  136. Log.e("MYLatLonLocationService", ll.toString());
  137. Latitude = Double.toString(ll.getLatitude());
  138. Longitude = Double.toString(ll.getLongitude());
  139. Toast.makeText(getApplicationContext(), Latitude + "n" + Longitude, Toast.LENGTH_LONG).show();
  140. Log.e("Lat&Lon", Latitude + "n" + Longitude);
  141.  
  142. latCurrent = ll.getLatitude();
  143. lngCurrent = ll.getLongitude();
  144. LatLng locCurrent = new LatLng(latCurrent, lngCurrent);
  145. markerCurrentLoc = mMap.addMarker(new MarkerOptions()
  146. .position(locCurrent)
  147. .title("My Location"));
  148. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  149. != PackageManager.PERMISSION_GRANTED &&
  150. ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
  151. != PackageManager.PERMISSION_GRANTED) {
  152.  
  153. return;
  154. }
  155. LocationServices.FusedLocationApi.requestLocationUpdates(gac, locationRequest, this);
  156. }
  157.  
  158.  
  159. //=========== DRAW CURRENT LOCATION==============//
  160. private void drawAllMarker() {
  161.  
  162. LatLng locCurrent = new LatLng(latCurrent, lngCurrent);
  163. //mMap.addMarker(new MarkerOptions().position(locCurrent).title("My Location"));
  164.  
  165. markerCurrentLoc = mMap.addMarker(new MarkerOptions()
  166. .position(locCurrent)
  167. .title("My Location"));
  168. /*mMap.moveCamera(CameraUpdateFactory.newLatLng(locCurrent));
  169. CameraPosition cameraPosition = new CameraPosition.Builder().target(
  170. locCurrent).zoom(13).build();
  171. mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));*/
  172. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  173. != PackageManager.PERMISSION_GRANTED &&
  174. ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
  175. != PackageManager.PERMISSION_GRANTED) {
  176.  
  177. return;
  178. }
  179. LocationServices.FusedLocationApi.requestLocationUpdates(gac, locationRequest, this);
  180. }
  181.  
  182.  
  183. //=========== onRequestPermissionsResult ==============//
  184. @Override
  185. public void onRequestPermissionsResult(
  186. int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  187.  
  188. switch (requestCode) {
  189. case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
  190. // If request is cancelled, the result arrays are empty.
  191. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  192. Toast.makeText(MapsActivity.this, "Permission was granted!", Toast.LENGTH_LONG).show();
  193.  
  194. try {
  195. LocationServices.FusedLocationApi.requestLocationUpdates(
  196. gac, locationRequest, this);
  197. } catch (SecurityException e) {
  198. Toast.makeText(MapsActivity.this, "SecurityException:n" + e.toString(), Toast.LENGTH_LONG).show();
  199. }
  200. } else {
  201. Toast.makeText(MapsActivity.this, "Permission denied!", Toast.LENGTH_LONG).show();
  202. }
  203. return;
  204. }
  205. }
  206. }
  207.  
  208. @Override
  209. public void onConnectionSuspended(int i) {
  210.  
  211. }
  212.  
  213. @Override
  214. public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  215. Toast.makeText(MapsActivity.this, "onConnectionFailed: n" + connectionResult.toString(),
  216. Toast.LENGTH_LONG).show();
  217. Log.d("DDD", connectionResult.toString());
  218. }
  219.  
  220. private void updateUI(Location loc) {
  221. Log.d(TAG, "updateUI");
  222.  
  223. /*tvLatitude.setText(Double.toString(loc.getLatitude()));
  224. tvLongitude.setText(Double.toString(loc.getLongitude()));
  225. tvTime.setText(DateFormat.getTimeInstance().format(loc.getTime()));*/
  226.  
  227. TestBtn.setText(Double.toString(loc.getLatitude()));
  228.  
  229.  
  230. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  231. != PackageManager.PERMISSION_GRANTED &&
  232. ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  233. // TODO: Consider calling
  234.  
  235. return;
  236. }
  237. ll = LocationServices.FusedLocationApi.getLastLocation(gac);
  238. Log.d(TAG, "LastLocation: " + (ll == null ? "NO LastLocation" : ll.toString()));
  239. Log.e("MYLatLonLocationService", ll.toString());
  240. Latitude = Double.toString(ll.getLatitude());
  241. Longitude = Double.toString(ll.getLongitude());
  242. Toast.makeText(getApplicationContext(), Latitude + "n" + Longitude, Toast.LENGTH_LONG).show();
  243. Log.e("Lat&Lon", Latitude + "n" + Longitude);
  244.  
  245. if (markerCurrentLoc != null) {
  246. markerCurrentLoc.remove();
  247.  
  248. latCurrent = ll.getLatitude();
  249. lngCurrent = ll.getLongitude();
  250. LatLng locCurrent = new LatLng(latCurrent, lngCurrent);
  251. markerCurrentLoc = mMap.addMarker(new MarkerOptions()
  252. .position(locCurrent)
  253. .title("My Location"));
  254. CameraPosition cameraPosition = new CameraPosition.Builder().target(
  255. locCurrent).zoom(12).build();
  256. mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
  257.  
  258. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  259. != PackageManager.PERMISSION_GRANTED &&
  260. ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
  261. != PackageManager.PERMISSION_GRANTED) {
  262.  
  263. return;
  264. }
  265. LocationServices.FusedLocationApi.requestLocationUpdates(gac, locationRequest, this);
  266.  
  267. }else {
  268.  
  269.  
  270. latCurrent = ll.getLatitude();
  271. lngCurrent = ll.getLongitude();
  272. LatLng locCurrent = new LatLng(latCurrent, lngCurrent);
  273. markerCurrentLoc = mMap.addMarker(new MarkerOptions()
  274. .position(locCurrent)
  275. .title("My Location"));
  276. markerCurrentLoc = mMap.addMarker(new MarkerOptions()
  277. .position(locCurrent)
  278. .title("My Location"));
  279. CameraPosition cameraPosition = new CameraPosition.Builder().target(
  280. locCurrent).zoom(12).build();
  281. mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
  282.  
  283. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
  284. != PackageManager.PERMISSION_GRANTED &&
  285. ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
  286. != PackageManager.PERMISSION_GRANTED) {
  287.  
  288. return;
  289. }
  290. LocationServices.FusedLocationApi.requestLocationUpdates(gac, locationRequest, this);
  291. }
  292. }
  293.  
  294. private boolean isLocationEnabled() {
  295. LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  296. return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
  297. locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
  298. }
  299.  
  300. private boolean isGooglePlayServicesAvailable() {
  301. final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
  302. GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
  303. int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
  304. if (resultCode != ConnectionResult.SUCCESS) {
  305. if (apiAvailability.isUserResolvableError(resultCode)) {
  306. apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
  307. .show();
  308. } else {
  309. Log.d(TAG, "This device is not supported.");
  310. finish();
  311. }
  312. return false;
  313. }
  314. Log.d(TAG, "This device is supported.");
  315. return true;
  316. }
  317.  
  318. private void showAlert() {
  319. final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
  320. dialog.setTitle("Enable Location")
  321. .setMessage("Your Locations Settings is set to 'Off'.nPlease Enable Location to " +
  322. "use this app")
  323. .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
  324. @Override
  325. public void onClick(DialogInterface paramDialogInterface, int paramInt) {
  326.  
  327. Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  328. startActivity(myIntent);
  329. }
  330. })
  331. .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
  332. @Override
  333. public void onClick(DialogInterface paramDialogInterface, int paramInt) {
  334.  
  335. }
  336. });
  337. dialog.show();
  338. }
  339.  
  340. //=========================== PLACES API=======================//
  341.  
  342. public void getPlacesApi() {
  343.  
  344. autocompleteFragment = (PlaceAutocompleteFragment)
  345. getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
  346. autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
  347. @Override
  348. public void onPlaceSelected(Place place) {
  349. // TODO: Get info about the selected place.
  350. Log.i(TAG, "Place: " + place.getName());
  351.  
  352.  
  353. if (markerDesti != null) {
  354. markerDesti.remove();
  355.  
  356. LatDesti = place.getLatLng().latitude;
  357. LonDesti = place.getLatLng().longitude;
  358. Log.e("LatLonDest", String.valueOf(LatDesti));
  359. DestiLoc = new LatLng(LatDesti, LonDesti);
  360. markerDesti = mMap.addMarker(new MarkerOptions()
  361. .position(DestiLoc)
  362. .title("My Destination"));
  363. mMap.moveCamera(CameraUpdateFactory.newLatLng(DestiLoc));
  364. CameraPosition cameraPosition = new CameraPosition.Builder().target(
  365. DestiLoc).zoom(12).build();
  366. mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
  367.  
  368. mGeofenceList.add(new Geofence.Builder()
  369. .setRequestId("120")
  370. .setCircularRegion(
  371. LatDesti,
  372. LonDesti,
  373. Constants.GEOFENCE_RADIUS_IN_METERS
  374. )
  375. .setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
  376. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
  377. Geofence.GEOFENCE_TRANSITION_EXIT)
  378. .build());
  379.  
  380. //geofancingResultCallBack.regesterAllGeofance();
  381. //geofancingResultCallBack.myUpdateGeoFance(LatDesti, LonDesti);
  382. //geofancingResultCallBack.getGeofencingRequest();
  383. //geofancingResultCallBack.getmPendingIntent();
  384.  
  385.  
  386. } else {
  387.  
  388. LatDesti = place.getLatLng().latitude;
  389. LonDesti = place.getLatLng().longitude;
  390. Log.e("LatLonDest", String.valueOf(LatDesti));
  391. DestiLoc = new LatLng(LatDesti, LonDesti);
  392. markerDesti = mMap.addMarker(new MarkerOptions()
  393. .position(DestiLoc)
  394. .title("My Destination"));
  395. mMap.moveCamera(CameraUpdateFactory.newLatLng(DestiLoc));
  396. CameraPosition cameraPosition = new CameraPosition.Builder().target(
  397. DestiLoc).zoom(12).build();
  398. mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
  399.  
  400. mGeofenceList.add(new Geofence.Builder()
  401. .setRequestId("120")
  402. .setCircularRegion(
  403. LatDesti,
  404. LonDesti,
  405. Constants.GEOFENCE_RADIUS_IN_METERS
  406. )
  407. .setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
  408. .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
  409. Geofence.GEOFENCE_TRANSITION_EXIT)
  410. .build());
  411.  
  412. //geofancingResultCallBack.regesterAllGeofance();
  413. //geofancingResultCallBack.myUpdateGeoFance(LatDesti, LonDesti);
  414. //geofancingResultCallBack.getGeofencingRequest();
  415. //geofancingResultCallBack.getmPendingIntent();
  416.  
  417.  
  418. }
  419.  
  420. if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  421. // TODO: Consider calling
  422.  
  423. return;
  424. }
  425. mGeofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent())
  426. .addOnSuccessListener(MapsActivity.this, new OnSuccessListener<Void>() {
  427. @Override
  428. public void onSuccess(Void aVoid) {
  429. // Geofences added
  430. Log.e("Geofencing Location service Api Client", "successfully added");
  431.  
  432. }
  433. })
  434. .addOnFailureListener(MapsActivity.this, new OnFailureListener() {
  435. @Override
  436. public void onFailure(@NonNull Exception e) {
  437. // Failed to add geofences
  438. Log.e("Geofencing Location service Api Client", "unsuccessful");
  439. }
  440. });
  441.  
  442. //============================================================================================//
  443.  
  444. }
  445.  
  446. @Override
  447. public void onError(Status status) {
  448. // TODO: Handle the error.
  449. Log.i(TAG, "An error occurred: " + status);
  450. }
  451. });
  452. }
  453.  
  454.  
  455. @Override
  456. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  457. super.onActivityResult(requestCode, resultCode, data);
  458. //autocompleteFragment.onActivityResult(requestCode, resultCode, data);
  459. if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
  460. if (resultCode == RESULT_OK) {
  461. Place place = PlaceAutocomplete.getPlace(this, data);
  462. Log.i(TAG, "Place:" + place.toString());
  463. } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
  464. Status status = PlaceAutocomplete.getStatus(this, data);
  465. Log.i(TAG, status.getStatusMessage());
  466. } else if (requestCode == RESULT_CANCELED) {
  467.  
  468. }
  469. }
  470. }
  471.  
  472.  
  473. //============================== GEO FANCING=================================//
  474.  
  475. private GeofencingRequest getGeofencingRequest() {
  476. GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
  477. builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
  478. builder.addGeofences(mGeofenceList);
  479. return builder.build();
  480. }
  481. private PendingIntent getGeofencePendingIntent() {
  482. // Reuse the PendingIntent if we already have it.
  483. if (mGeofencePendingIntent != null) {
  484. return mGeofencePendingIntent;
  485. }
  486. Intent intent = new Intent(this, BroadcastReciver.class);
  487. // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
  488. // calling addGeofences() and removeGeofences().
  489. mGeofencePendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.
  490. FLAG_UPDATE_CURRENT);
  491. return mGeofencePendingIntent;
  492. }
  493.  
  494. public class BroadcastReciver extends BroadcastReceiver {
  495.  
  496. //Placer Geofence intent action name
  497. public static final String INTENT_ACTION_TRIGGER_FIRED = "com.placer.action.TRIGGER_FIRED";
  498. public static final String TAG1 = GeofanceBroadCastReciver.class.getSimpleName();
  499. private static final String TAG = "GeofenceTransitions";
  500.  
  501. public BroadcastReciver() {
  502. }
  503.  
  504. @Override
  505. public void onReceive(Context context, Intent intent) {
  506.  
  507. /*GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
  508. if (geofencingEvent.hasError()){
  509.  
  510. Log.e(TAG,String.format("Error code :%d",geofencingEvent.getErrorCode()));
  511. return;
  512. }
  513.  
  514. int geofenceTransition = geofencingEvent.getGeofenceTransition();
  515. if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER){
  516. Log.e("Geo Fance ENTER","Geo Fance ENTER");
  517. Toast.makeText(context, "Geo Fance ENTER", Toast.LENGTH_SHORT).show();
  518.  
  519.  
  520. }else if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT){
  521. Log.e("Geo Fance EXIT","Geo Fance EXIT");
  522. Toast.makeText(context,"Geo Fance EXIT",Toast.LENGTH_SHORT).show();
  523.  
  524. }
  525. else {
  526.  
  527. Log.e(TAG,String.format("Unknown Transition :%",geofenceTransition));
  528. return;
  529. }
  530.  
  531. sendNotification(context,geofenceTransition);*/
  532.  
  533.  
  534. if (intent.getAction().equals(INTENT_ACTION_TRIGGER_FIRED)) {
  535.  
  536. Log.e("ReciverWorking","ReciverWorking");
  537. GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
  538. if (geofencingEvent.hasError()) {
  539. Log.e(TAG, "Goefencing Error " + geofencingEvent.getErrorCode());
  540. return;
  541. }
  542. // Get the transition type.
  543. int geofenceTransition = geofencingEvent.getGeofenceTransition();
  544. Log.i(TAG, "geofenceTransition = " + geofenceTransition + " Enter : " + Geofence.GEOFENCE_TRANSITION_ENTER + "Exit : " + Geofence.GEOFENCE_TRANSITION_EXIT);
  545. if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL){
  546. showNotification("Congrats!!!", "You have reached your destination..",context);
  547. Toast.makeText(context,"Enter the Location",Toast.LENGTH_SHORT).show();
  548. }
  549. else if(geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
  550. Log.i(TAG, "Showing Notification...");
  551. showNotification("Exited", "Exited the Location",context);
  552. Toast.makeText(context,"Exited the Location",Toast.LENGTH_SHORT).show();
  553.  
  554. } else {
  555. // Log the error.
  556. showNotification("Error", "Error",context);
  557. Log.e(TAG, "Error ");
  558. }
  559.  
  560. }else {
  561. throw new UnsupportedOperationException("Not yet implemented");
  562. }
  563. }
  564. private void sendNotification(Context context,int transationType){
  565.  
  566. Intent notificationIntent = new Intent(context,MapsActivity.class);
  567. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
  568. stackBuilder.addParentStack(MapsActivity.class);
  569. stackBuilder.addNextIntent(notificationIntent);
  570.  
  571. PendingIntent notificationpendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
  572.  
  573. NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
  574. if (transationType == Geofence.GEOFENCE_TRANSITION_ENTER){
  575. builder.setSmallIcon(R.mipmap.ic_launcher);
  576. builder.setContentTitle("Entered");
  577. }else if (transationType == Geofence.GEOFENCE_TRANSITION_EXIT) {
  578. builder.setSmallIcon(R.mipmap.ic_launcher);
  579. builder.setContentTitle("Exit");
  580. }
  581.  
  582. builder.setContentText("Touch to launch the app");
  583. builder.setContentIntent(notificationpendingIntent);
  584. builder.setAutoCancel(true);
  585. NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
  586. notificationManager.notify(0, builder.build());
  587. }
  588.  
  589.  
  590.  
  591.  
  592. public void showNotification(String text, String bigText,Context context) {
  593. // 1. Create a NotificationManager
  594. NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
  595. // 2. Create a PendingIntent for AllGeofencesActivity
  596. Intent intent = new Intent(context, MapsActivity.class);
  597. intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
  598. PendingIntent pendingNotificationIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  599. // 3. Create and send a notification
  600. Notification notification = new NotificationCompat.Builder(context)
  601. .setSmallIcon(R.mipmap.ic_launcher)
  602. .setContentTitle("Congrats!!!")
  603. .setContentText("You Have reached the destination")
  604. .setContentIntent(pendingNotificationIntent)
  605. .setStyle(new NotificationCompat.BigTextStyle().bigText(bigText))
  606. .setPriority(NotificationCompat.PRIORITY_HIGH)
  607. .setAutoCancel(true)
  608. .build();
  609. notificationManager.notify(0, notification);
  610.  
  611. }
  612.  
  613. <?xml version="1.0" encoding="utf-8"?>
  614.  
  615. <!--
  616. The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
  617. Google Maps Android API v2, but you must specify either coarse or fine
  618. location permissions for the 'MyLocation' functionality.
  619. -->
  620. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  621. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  622. <uses-permission android:name="android.permission.INTERNET" />
  623. <uses-feature android:name="android.hardware.location.gps" />
  624.  
  625. <application
  626. android:allowBackup="true"
  627. android:icon="@mipmap/ic_launcher"
  628. android:label="@string/app_name"
  629. android:supportsRtl="true"
  630. android:theme="@style/AppTheme">
  631.  
  632.  
  633. <meta-data
  634. android:name="com.google.android.geo.API_KEY"
  635. android:value="@string/google_maps_key" />
  636.  
  637. <activity
  638. android:name=".main.MapsActivity"
  639. android:label="@string/title_activity_maps">
  640. <intent-filter>
  641. <action android:name="android.intent.action.MAIN" />
  642.  
  643. <category android:name="android.intent.category.LAUNCHER" />
  644. </intent-filter>
  645. </activity>
  646.  
  647. <service
  648. android:name=".adapters.GeofenceTransitionsIntentService"
  649. android:exported="true" />
  650.  
  651. <receiver
  652. android:name="com.map.pallabedp.locationbasedtracking.main.BroadcastReciver"
  653. android:enabled="true"
  654. android:exported="false">
  655. <intent-filter>
  656. <action android:name="com.placer.action.TRIGGER_FIRED" />
  657. <action android:name="my.action.string" />
  658. <action android:name="com.map.pallabedp.locationbasedtracking.main.BroadcastReciver"/>
  659. </intent-filter>
  660. </receiver>
  661.  
  662. </application>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement