Java tutorial
package com.licenta.android.licenseapp.location; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonObjectRequest; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.GeofencingRequest; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.licenta.android.licenseapp.MyApplication; import com.licenta.android.licenseapp.R; import com.licenta.android.licenseapp.fragment.TabFragment; import com.licenta.android.licenseapp.fragment.UpdatableFragment; import com.licenta.android.licenseapp.model.LocationPoint; import com.licenta.android.licenseapp.model.Venue; import org.json.JSONObject; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; import io.realm.Realm; import io.realm.RealmResults; /** * Created by oana.ilovan on 27.12.2015. */ public class MapFragment extends Fragment implements TabFragment, UpdatableFragment, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private SupportMapFragment mSupportMapFragment; private GoogleMap mMap; private GoogleApiClient mGoogleApiClient; private LocationRequest mLocationRequest; private Realm mRealm; private List<Geofence> mGeofenceList = new ArrayList<>(); // private RealmChangeListener mRealmListener = new RealmChangeListener() { // @Override // public void onChange() { // // } // }; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_maps, container, false); FragmentManager fragmentManager = getChildFragmentManager(); // Obtain the SupportMapFragment and get notified when the map is ready to be used. mSupportMapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.map_container); if (mSupportMapFragment == null) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); mSupportMapFragment = SupportMapFragment.newInstance(); fragmentTransaction.replace(R.id.map_container, mSupportMapFragment).commit(); } mSupportMapFragment.getMapAsync(this); Button eventBtn = (Button) view.findViewById(R.id.event_btn); eventBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getGeofencesList(); } }); Button showBtn = (Button) view.findViewById(R.id.show_btn); showBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onShow(v); } }); Button clearBtn = (Button) view.findViewById(R.id.clear_btn); clearBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClear(v); } }); // Create an instance of GoogleAPIClient. if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this) .addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); } return view; } public void onStart() { super.onStart(); mRealm = Realm.getDefaultInstance(); mGoogleApiClient.connect(); } public void onStop() { super.onStop(); mRealm.close(); mGoogleApiClient.disconnect(); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; onShow(null); } // @Override // public void onConnected(Bundle bundle) { // Location lastLocation = LocationServices.FusedLocationApi.getLastLocation( // mGoogleApiClient); // if (lastLocation == null) { // int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), // Manifest.permission.ACCESS_FINE_LOCATION); // if (permissionCheck == PackageManager.PERMISSION_GRANTED) { // LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); // } // // } else { // handleNewLocation(lastLocation); // } // // } private void addMarker(LatLng latLng, String title, String snippet, int resId) { MarkerOptions options = new MarkerOptions().title(title).snippet(snippet).position(latLng); if (resId != 0) options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET)); //icon(getResources().getDrawable(resId)); mMap.addMarker(options); } public void onShow(View view) { LatLng lastKnownLatLng = null; RealmResults<LocationPoint> result = mRealm.where(LocationPoint.class).findAll(); for (LocationPoint point : result) { lastKnownLatLng = new LatLng(point.getLatitude(), point.getLongitude()); addMarker(lastKnownLatLng, new SimpleDateFormat("dd/MM/yyyy hh:mm").format(point.getTimestamp()), "", 0); } if (lastKnownLatLng != null) { mMap.moveCamera(CameraUpdateFactory.newLatLng(lastKnownLatLng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f)); } try { Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault()); List<Address> addressList = geocoder.getFromLocationName("Piata Unirii nr. 30, Cluj-Napoca", 1); LatLng eventLatLng = new LatLng(addressList.get(0).getLatitude(), addressList.get(0).getLongitude()); addMarker(eventLatLng, "Dominic Miller (from Sting) and Miles Bould", "Muzeul de Arta", R.drawable.ic_action_maps_local_play); addressList = geocoder.getFromLocationName("Strada George Bariiu 26-28, Cluj-Napoca", 1); LatLng eventLatLng2 = new LatLng(addressList.get(0).getLatitude(), addressList.get(0).getLongitude()); addMarker(eventLatLng2, "Facultatea de Automatica si Calculatoare", "", R.drawable.ic_action_maps_local_play); } catch (IOException e) { e.printStackTrace(); } } public void onClear(View view) { mRealm.beginTransaction(); mRealm.clear(LocationPoint.class); mRealm.commitTransaction(); mMap.clear(); } private void getGeofencesList() { mRealm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm bgRealm) { Venue work = new Venue(); work.setId((long) 123); work.setLatitude(46.77005); work.setLongitude(23.60712); bgRealm.copyToRealmOrUpdate(work); Venue home = new Venue(); home.setId((long) 0); home.setLatitude(46.75056); home.setLongitude(23.55608); bgRealm.copyToRealmOrUpdate(home); } }, new Realm.Transaction.Callback() { @Override public void onSuccess() { RealmResults<Venue> venues = mRealm.where(Venue.class).equalTo("id", 123).findAll(); for (Venue venue : venues) { mGeofenceList.add(new Geofence.Builder() // Set the request ID of the geofence. This is a string to identify this // geofence. .setRequestId(venue.getId().toString()) .setCircularRegion(venue.getLatitude(), venue.getLongitude(), 50) .setExpirationDuration(60000) // .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | // Geofence.GEOFENCE_TRANSITION_EXIT) .setTransitionTypes( Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) //.setLoiteringDelay(2) .build()); } startGeofencingService(); } }); } void startGeofencingService() { LocationServices.GeofencingApi .addGeofences(mGoogleApiClient, getGeofencingRequest(), getGeofencePendingIntent()) .setResultCallback(new ResultCallback<Status>() { @Override public void onResult(Status status) { Toast.makeText(getActivity(), "Comes the voice of the living god", Toast.LENGTH_SHORT) .show(); } }); } private GeofencingRequest getGeofencingRequest() { GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER); builder.addGeofences(mGeofenceList); return builder.build(); } private PendingIntent getGeofencePendingIntent() { // Reuse the PendingIntent if we already have it. // if (mGeofencePendingIntent != null) { // return mGeofencePendingIntent; // } Intent intent = new Intent(getActivity(), GeofenceTransitionsService.class); // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when // calling addGeofences() and removeGeofences(). return PendingIntent.getService(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } private void makeRequest() { String tag_json_obj = "json_obj_req"; String url = "http://api.bandsintown.com/artists/Metallica/events/search.json?api_version=2.0" + "&app_id=" + MyApplication.TAG; final ProgressDialog pDialog = new ProgressDialog(getActivity()); pDialog.setMessage("Loading..."); pDialog.show(); JsonObjectRequest jsonObjReq; jsonObjReq = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(MyApplication.TAG, response.toString()); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(MyApplication.TAG, "Error: " + error.getMessage()); // hide the progress dialog pDialog.hide(); } }); // Adding request to request queue MyApplication.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj); } @Override public String getTitle() { return "MAP"; } @Override public void update() { onShow(null); } @Override public void onConnected(Bundle bundle) { } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } }