Commit a18edafa authored by Paded's avatar Paded

first commit

parent 17eedad4
...@@ -19,7 +19,7 @@ android { ...@@ -19,7 +19,7 @@ android {
} }
dependencies { dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar']) implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:cardview-v7:26.1.0' implementation 'com.android.support:cardview-v7:26.1.0'
compile 'com.android.support:design:26.1.0' compile 'com.android.support:design:26.1.0'
...@@ -27,6 +27,7 @@ dependencies { ...@@ -27,6 +27,7 @@ dependencies {
implementation 'com.google.firebase:firebase-auth:11.6.0' implementation 'com.google.firebase:firebase-auth:11.6.0'
implementation 'com.google.firebase:firebase-database:11.6.0' implementation 'com.google.firebase:firebase-database:11.6.0'
implementation 'com.google.android.gms:play-services-location:11.6.0' implementation 'com.google.android.gms:play-services-location:11.6.0'
implementation 'com.google.android.gms:play-services-maps:11.6.0'
testImplementation 'junit:junit:4.12' testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application <application
android:allowBackup="true" android:allowBackup="true"
...@@ -13,6 +14,11 @@ ...@@ -13,6 +14,11 @@
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/AppTheme"> android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<activity <activity
android:launchMode="singleTop" android:launchMode="singleTop"
android:name=".MainActivity" android:name=".MainActivity"
...@@ -39,6 +45,11 @@ ...@@ -39,6 +45,11 @@
android:name=".TrackerService3" android:name=".TrackerService3"
android:enabled="true" android:enabled="true"
android:exported="true"></service> android:exported="true"></service>
<service
android:name=".GEOFENCE.GeofenceRegistrationService"
android:enabled="true"
android:exported="true"></service>
</application> </application>
</manifest> </manifest>
\ No newline at end of file
package ubontransitdriver.paded.com.ubontransitdriver.GEOFENCE;
import com.google.android.gms.maps.model.LatLng;
import java.util.HashMap;
/**
* Created by brijesh on 15/4/17.
*/
public class Constants {
public static final String GEOFENCE_ID_STAN_UNI = "STAN_UNI";
public static final String GEOFENCE_ID_UBU= "BS00";
public static final float GEOFENCE_RADIUS_IN_METERS = 100;
/**
* Map for storing information about stanford university in the Stanford.
*/
public static final HashMap<String, LatLng> AREA_LANDMARKS = new HashMap<String, LatLng>();
static {
// stanford university.
AREA_LANDMARKS.put(GEOFENCE_ID_STAN_UNI, new LatLng(37.427476, -122.170262));
// San Francisco International Airport.
AREA_LANDMARKS.put(GEOFENCE_ID_UBU, new LatLng(15.122239, 104.906372));
}
}
package ubontransitdriver.paded.com.ubontransitdriver.GEOFENCE;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class GeofenceRegistrationService extends IntentService {
private static final String TAG = "GeoIntentService";
private FirebaseAuth auth;
private int bus_stop_size;
private String[] bus_stop_list;
private HashMap<String, Integer> AREA_LANDMARKS;
public GeofenceRegistrationService() {
super(TAG);
}
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
bus_stop_size = intent.getIntExtra("bus_stop_size",0);
bus_stop_list = intent.getStringArrayExtra("bus_stop_list");
AREA_LANDMARKS = new HashMap<String, Integer>();
Log.d(TAG, "onStartCommand: "+bus_stop_size);
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
auth = FirebaseAuth.getInstance();
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
Log.d(TAG, "onHandleIntent: "+geofencingEvent.getTriggeringLocation());
if (geofencingEvent.hasError()) {
Log.d(TAG, "GeofencingEvent error " + geofencingEvent.getErrorCode());
} else {
int transaction = geofencingEvent.getGeofenceTransition();
List<Geofence> geofences = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
String geofenceTransitionDetails = getGeofenceTransitionDetails(transaction, geofences);
Log.d(TAG, "onHandleIntent: "+geofenceTransitionDetails);
// Log.d(TAG, "onHandleIntent: "+geofences.size());
// Geofence geofence = geofences.get(0);
// if (transaction == Geofence.GEOFENCE_TRANSITION_ENTER && geofence.getRequestId().equals(Constants.GEOFENCE_ID_UBU)) {
// Log.d(TAG, "You are inside Stanford University");
// } else {
// Log.d(TAG, "You are outside Stanford University");
// }
}
}
private String getGeofenceTransitionDetails(int geofenceTransition, List<Geofence> triggeringGeofences) {
String geofenceTransitionString = getTransitionString(geofenceTransition);
Log.d(TAG, "getGeofenceTransitionTYPE "+geofenceTransition);
// Get the Ids of each geofence that was triggered.
ArrayList<String> triggeringGeofencesIdsList = new ArrayList<>();
for (Geofence geofence : triggeringGeofences) {
AREA_LANDMARKS.put(geofence.getRequestId(),geofenceTransition);
triggeringGeofencesIdsList.add(geofence.getRequestId());
}
String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
changeBusstopStatus();
return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
}
private String getTransitionString(int transitionType) {
switch (transitionType) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
return "Entered";
case Geofence.GEOFENCE_TRANSITION_EXIT:
return "Exited";
default:
return "Unknown Transition";
}
}
private void changeBusstopStatus(){
Log.d(TAG, "changeBusstopStatus: "+AREA_LANDMARKS);
FirebaseUser user = auth.getCurrentUser();
for (int i=0; i<bus_stop_size; i++){
final String path = "active_bus/" + user.getUid()+"/busstop/"+i+"/"+bus_stop_list[i];
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(path);
if(AREA_LANDMARKS.containsKey(bus_stop_list[i])&&AREA_LANDMARKS.get(bus_stop_list[i])==1){
Log.d(TAG, "changeBusstopStatus: CONTAIN IN");
ref.child("on_busstop_status").setValue(true);
}else if(AREA_LANDMARKS.containsKey(bus_stop_list[i])&&AREA_LANDMARKS.get(bus_stop_list[i])==2){
Log.d(TAG, "changeBusstopStatus: CONTAIN OUT");
ref.child("on_busstop_status").setValue(false);
ref.child("path_status").setValue(true);
}else{
}
// Log.d(TAG, "changeBusstopStatus: "+AREA_LANDMARKS.get(bus_stop_list[i]));
//
// if(AREA_LANDMARKS.containsKey(bus_stop_list[i])&&AREA_LANDMARKS.get(bus_stop_list[i])==1){
// Log.d(TAG, "changeBusstopStatus: "+bus_stop_list[i]+" TYPE"+AREA_LANDMARKS.get(bus_stop_list[i]));
// ref.child("status").setValue(true);
// }else {
// ref.child("status").setValue(false);
// }
}
}
}
...@@ -44,6 +44,7 @@ import com.google.android.gms.location.LocationSettingsResult; ...@@ -44,6 +44,7 @@ import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes; import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.DatabaseReference;
...@@ -76,29 +77,30 @@ public class MainActivity extends AppCompatActivity implements LocationListener ...@@ -76,29 +77,30 @@ public class MainActivity extends AppCompatActivity implements LocationListener
String user_id; String user_id;
String start_busstop_name; String start_busstop_name;
String stop_busstop_name; String stop_busstop_name;
String allbusStop;
String start_busstop_id; String start_busstop_id;
String stop_busstop_id; String stop_busstop_id;
int k = 0; int k = 0;
public static Context currentContext;
NotificationManager mNotificationManager; NotificationManager mNotificationManager;
private ValueEventListener eventListener1;
private DatabaseReference database;
DatabaseReference ref1;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout); setContentView(R.layout.main_layout);
MainActivity.currentContext = this;
database = FirebaseDatabase.getInstance().getReference();
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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; return;
} }
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);
...@@ -148,7 +150,7 @@ public class MainActivity extends AppCompatActivity implements LocationListener ...@@ -148,7 +150,7 @@ public class MainActivity extends AppCompatActivity implements LocationListener
bottomSheetBehavior = BottomSheetBehavior.from((View) bottomSheetView.getParent()); bottomSheetBehavior = BottomSheetBehavior.from((View) bottomSheetView.getParent());
btn_endtrip_cancel = (Button) bottomSheetView.findViewById(R.id.btn_endtrip_cancel); btn_endtrip_cancel = (Button) bottomSheetView.findViewById(R.id.btn_endtrip_cancel);
btn_endtrip_yes = (Button) bottomSheetView.findViewById(R.id.btn_endtrip_yes); btn_endtrip_yes = (Button) bottomSheetView.findViewById(R.id.btn_endtrip_yes);
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
// Attach a listener to read the data at our posts reference // Attach a listener to read the data at our posts reference
database.child("users/" + user.getUid()).addValueEventListener(new ValueEventListener() { database.child("users/" + user.getUid()).addValueEventListener(new ValueEventListener() {
@Override @Override
...@@ -179,6 +181,23 @@ public class MainActivity extends AppCompatActivity implements LocationListener ...@@ -179,6 +181,23 @@ public class MainActivity extends AppCompatActivity implements LocationListener
} }
}); });
DatabaseReference keyReference1 = FirebaseDatabase.getInstance().getReference().child("allbus/" + bus_id + "/direction/"+start_busstop_id);
keyReference1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
allbusStop = dataSnapshot.getValue(String.class);
if (user_status.equalsIgnoreCase("on")) {
startTrackerService(user_id, bus_id);
}
Log.d(TAG, "onDataChange: "+allbusStop);
Log.d(TAG, "onDataChange: USER Start bus"+start_busstop_id);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Read failed");
}
});
DatabaseReference keyReference_stop = FirebaseDatabase.getInstance().getReference().child("all_busstop/" + stop_busstop_id); DatabaseReference keyReference_stop = FirebaseDatabase.getInstance().getReference().child("all_busstop/" + stop_busstop_id);
keyReference_stop.addValueEventListener(new ValueEventListener() { keyReference_stop.addValueEventListener(new ValueEventListener() {
@Override @Override
...@@ -208,6 +227,8 @@ public class MainActivity extends AppCompatActivity implements LocationListener ...@@ -208,6 +227,8 @@ public class MainActivity extends AppCompatActivity implements LocationListener
} }
}); });
// DatabaseReference keyReference = FirebaseDatabase.getInstance().getReference().child("allbus/" + bus_id + "/bus_stop"); // DatabaseReference keyReference = FirebaseDatabase.getInstance().getReference().child("allbus/" + bus_id + "/bus_stop");
// keyReference.addValueEventListener(new ValueEventListener() { // keyReference.addValueEventListener(new ValueEventListener() {
// @Override // @Override
...@@ -311,7 +332,7 @@ public class MainActivity extends AppCompatActivity implements LocationListener ...@@ -311,7 +332,7 @@ public class MainActivity extends AppCompatActivity implements LocationListener
if (bus_id != null) { if (bus_id != null) {
Intent intent = new Intent(MainActivity.this, TrackerService3.class); Intent intent = new Intent(MainActivity.this, TrackerService3.class);
FirebaseDatabase database = FirebaseDatabase.getInstance(); FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("active_bus/" + bus_id); DatabaseReference myRef = database.getReference("active_bus");
myRef.child(user.getUid()).removeValue(); myRef.child(user.getUid()).removeValue();
stopService(intent); stopService(intent);
mNotificationManager.cancel(001); mNotificationManager.cancel(001);
...@@ -390,7 +411,7 @@ public class MainActivity extends AppCompatActivity implements LocationListener ...@@ -390,7 +411,7 @@ public class MainActivity extends AppCompatActivity implements LocationListener
// shadowView.setShadowTranslationZ(density * 2.0f); // 2.0 dp // shadowView.setShadowTranslationZ(density * 2.0f); // 2.0 dp
// shadowView.setShadowElevation(density * 4.0f); // 4.0 dp // shadowView.setShadowElevation(density * 4.0f); // 4.0 dp
onBusPositionChangeWatch();
} }
public void UpdateUserStatus(String user_id, boolean active_status) { public void UpdateUserStatus(String user_id, boolean active_status) {
...@@ -469,12 +490,15 @@ public class MainActivity extends AppCompatActivity implements LocationListener ...@@ -469,12 +490,15 @@ public class MainActivity extends AppCompatActivity implements LocationListener
} }
private void startTrackerService(String user_id, String bus_id) { private void startTrackerService(String user_id, String bus_id) {
Log.d("dddd", "startTrackerService: " + stop_busstop_name); Log.d(TAG, "startTrackerService: "+allbusStop);
String destination = stop_busstop_name; String destination = stop_busstop_name;
Intent intent = new Intent(this, TrackerService3.class); Intent intent = new Intent(this, TrackerService3.class);
intent.putExtra("user_id", user_id); intent.putExtra("user_id", user_id);
intent.putExtra("bus_id", bus_id); intent.putExtra("bus_id", bus_id);
intent.putExtra("destination", destination); intent.putExtra("destination", destination);
intent.putExtra("allbusStop", allbusStop);
intent.putExtra("start_busstop_id", start_busstop_id);
intent.putExtra("stop_busstop_id", stop_busstop_id);
startService(intent); startService(intent);
} }
...@@ -499,11 +523,18 @@ public class MainActivity extends AppCompatActivity implements LocationListener ...@@ -499,11 +523,18 @@ public class MainActivity extends AppCompatActivity implements LocationListener
.setContentText("Tracking, tap to open") .setContentText("Tracking, tap to open")
.setOngoing(true); .setOngoing(true);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent); Intent intent = new Intent(this, MainActivity.currentContext.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
// PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
// new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
...@@ -514,6 +545,8 @@ public class MainActivity extends AppCompatActivity implements LocationListener ...@@ -514,6 +545,8 @@ public class MainActivity extends AppCompatActivity implements LocationListener
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
bottomSheetDialog.dismiss();
MainActivity.currentContext = this;
} }
...@@ -523,9 +556,19 @@ public class MainActivity extends AppCompatActivity implements LocationListener ...@@ -523,9 +556,19 @@ public class MainActivity extends AppCompatActivity implements LocationListener
} }
@Override
public void onBackPressed() {
if(user_status.equalsIgnoreCase("on")){
Toast.makeText(MainActivity.this, "End your trip before close app", Toast.LENGTH_SHORT).show();
}else{
super.onBackPressed();
}
}
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
MainActivity.currentContext = this;
// LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// //
...@@ -685,4 +728,27 @@ public class MainActivity extends AppCompatActivity implements LocationListener ...@@ -685,4 +728,27 @@ public class MainActivity extends AppCompatActivity implements LocationListener
alert = builder.create(); alert = builder.create();
alert.show(); alert.show();
} }
public void onBusPositionChangeWatch() {
FirebaseUser user = auth.getCurrentUser();
ref1 = database.child("active_bus/" + user.getUid());
eventListener1 = ref1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("ddddd", "onDataChange: "+dataSnapshot.child("time").getValue(String.class));
// for (DataSnapshot ds : dataSnapshot.getChildren()) {
// Log.d("ddddd", "onDataChange: "+ds.getKey());
// }
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
} }
package ubontransitdriver.paded.com.ubontransitdriver; package ubontransitdriver.paded.com.ubontransitdriver;
import android.app.PendingIntent;
import android.app.Service; import android.app.Service;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
...@@ -15,21 +16,36 @@ import android.Manifest; ...@@ -15,21 +16,36 @@ import android.Manifest;
import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient; 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.FusedLocationProviderClient; import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingRequest;
import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import ubontransitdriver.paded.com.ubontransitdriver.GEOFENCE.Constants;
import ubontransitdriver.paded.com.ubontransitdriver.GEOFENCE.GeofenceRegistrationService;
public class TrackerService3 extends Service implements public class TrackerService3 extends Service implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{ GoogleApiClient.OnConnectionFailedListener {
FusedLocationProviderClient mFusedLocationClient; FusedLocationProviderClient mFusedLocationClient;
GoogleApiClient mGoogleApiClient; GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest; LocationRequest mLocationRequest;
...@@ -37,6 +53,25 @@ public class TrackerService3 extends Service implements ...@@ -37,6 +53,25 @@ public class TrackerService3 extends Service implements
private String user_id; private String user_id;
private String bus_id; private String bus_id;
private String destination; private String destination;
private String allbusStop = "";
private String start_busstop_id;
private String stop_busstop_id;
private PendingIntent pendingIntent;
private boolean isMonitoring = false;
private ArrayList<Geofence> mGeofenceList;
private HashMap<String, LatLng> AREA_LANDMARKS;
private String GEOFENCE_ID;
private float GEOFENCE_RADIUS_IN_METERS = 50;
private DatabaseReference database;
private ValueEventListener eventListener1;
private ValueEventListener eventListener2;
DatabaseReference ref1;
DatabaseReference ref2;
String[] bus_stop;
@Nullable @Nullable
@Override @Override
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
...@@ -45,11 +80,28 @@ public class TrackerService3 extends Service implements ...@@ -45,11 +80,28 @@ public class TrackerService3 extends Service implements
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("dddd", "onStartCommand: ");
user_id = intent.getStringExtra("user_id"); user_id = intent.getStringExtra("user_id");
bus_id = intent.getStringExtra("bus_id"); bus_id = intent.getStringExtra("bus_id");
destination = intent.getStringExtra("destination"); destination = intent.getStringExtra("destination");
Log.d(TAG, "onStartCommand: "+user_id+" "+bus_id); allbusStop = intent.getStringExtra("allbusStop");
start_busstop_id = intent.getStringExtra("start_busstop_id");
stop_busstop_id = intent.getStringExtra("stop_busstop_id");
database = FirebaseDatabase.getInstance().getReference();
Log.d(TAG, "onStartCommand: allbus get from intent " + allbusStop + destination);
bus_stop = allbusStop.split(",");
// Empty list for storing geofences.
mGeofenceList = new ArrayList<>();
AREA_LANDMARKS = new HashMap<String, LatLng>();
getGeofenceList();
addAllBusStop();
// Log.d(TAG, "onStartCommand: "+user_id+" "+bus_id);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (mGoogleApiClient != null && mFusedLocationClient != null) { if (mGoogleApiClient != null && mFusedLocationClient != null) {
requestLocationUpdates(); requestLocationUpdates();
...@@ -68,6 +120,156 @@ public class TrackerService3 extends Service implements ...@@ -68,6 +120,156 @@ public class TrackerService3 extends Service implements
mGoogleApiClient.connect(); mGoogleApiClient.connect();
} }
private void getGeofenceList() {
ref1 = database.child("all_busstop");
eventListener1 = ref1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if(Arrays.asList(bus_stop).contains(ds.getKey())){
getBusStopDetail(ds.getKey());
}else {
}
}
}
@Override
public void onCancelled (DatabaseError databaseError){
}
});
}
public void getBusStopDetail(String itemKey) {
ref2 = database.child("all_busstop/" + itemKey);
eventListener2 = ref2.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
GEOFENCE_ID = dataSnapshot.getKey();
double lat = dataSnapshot.child("lat").getValue(Double.class);
double lng = dataSnapshot.child("lng").getValue(Double.class);
if(AREA_LANDMARKS.containsKey(GEOFENCE_ID)){
}else{
AREA_LANDMARKS.put(GEOFENCE_ID,new LatLng(lat,lng));
if(AREA_LANDMARKS.size()==bus_stop.length){
// AREA_LANDMARKS.put("BS00",new LatLng(15.112765839672141,104.896290153265));
populateGeofenceList();
startGeofencing();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void populateGeofenceList() {
Log.d(TAG, "populateGeofenceList: "+AREA_LANDMARKS);
for (Map.Entry<String, LatLng> entry : AREA_LANDMARKS.entrySet()) {
mGeofenceList.add(new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId(entry.getKey())
// Set the circular region of this geofence.
.setCircularRegion(
entry.getValue().latitude,
entry.getValue().longitude,
GEOFENCE_RADIUS_IN_METERS
)
// Set the expiration duration of the geofence. This geofence gets automatically
// removed after this period of time.
.setExpirationDuration(Geofence.NEVER_EXPIRE)
// Set the transition types of interest. Alerts are only generated for these
// transition. We track entry and exit transitions in this sample.
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
// Create the geofence.
.build());
}
}
private PendingIntent getGeofencePendingIntent() {
if (pendingIntent != null) {
return pendingIntent;
}
Intent intent = new Intent(this, GeofenceRegistrationService.class);
intent.putExtra("bus_stop_size", bus_stop.length);
intent.putExtra("bus_stop_list", bus_stop);
return PendingIntent.getService(this, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
}
private void startGeofencing() {
Log.d(TAG, "Start geofencing monitoring call");
if (!mGoogleApiClient.isConnected()) {
Log.d(TAG, "Google API client not connected");
} else {
try {
LocationServices.GeofencingApi.addGeofences(mGoogleApiClient, getGeofencingRequest(), getGeofencePendingIntent()).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess()) {
Log.d(TAG, "Successfully Geofencing Connected");
} else {
Log.d(TAG, "Failed to add Geofencing " + status.getStatus());
}
}
});
} catch (SecurityException e) {
Log.d(TAG, e.getMessage());
}
}
isMonitoring = true;
}
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
// The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a
// GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device
// is already inside that geofence.
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
// Add the geofences to be monitored by geofencing service.
builder.addGeofences(mGeofenceList);
// Return a GeofencingRequest.
return builder.build();
}
private void stopGeoFencing() {
pendingIntent = getGeofencePendingIntent();
LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient, pendingIntent)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if (status.isSuccess())
Log.d(TAG, "Stop geofencing");
else
Log.d(TAG, "Not stop geofencing");
}
});
isMonitoring = false;
}
@Override @Override
public void onDestroy() { public void onDestroy() {
super.onDestroy(); super.onDestroy();
...@@ -79,8 +281,8 @@ public class TrackerService3 extends Service implements ...@@ -79,8 +281,8 @@ public class TrackerService3 extends Service implements
public void requestLocationUpdates() { public void requestLocationUpdates() {
mLocationRequest = new LocationRequest(); mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000); // two minute interval mLocationRequest.setInterval(2000); // two minute interval
mLocationRequest.setFastestInterval(5000); mLocationRequest.setFastestInterval(2000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this, if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) Manifest.permission.ACCESS_FINE_LOCATION)
...@@ -89,34 +291,66 @@ public class TrackerService3 extends Service implements ...@@ -89,34 +291,66 @@ public class TrackerService3 extends Service implements
} }
} }
LocationCallback mLocationCallback = new LocationCallback(){ LocationCallback mLocationCallback = new LocationCallback() {
@Override @Override
public void onLocationResult(LocationResult locationResult) { public void onLocationResult(LocationResult locationResult) {
final String path ="active_bus/"+bus_id+"/"+user_id; // final String path ="active_bus/"+bus_id+"/"+user_id;
final String path = "active_bus/" + user_id;
for (Location location : locationResult.getLocations()) { for (Location location : locationResult.getLocations()) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(path); DatabaseReference ref = FirebaseDatabase.getInstance().getReference(path);
ref.child("latitude").setValue(location.getLatitude()); ref.child("lat").setValue(location.getLatitude());
ref.child("longitude").setValue(location.getLongitude()); ref.child("lng").setValue(location.getLongitude());
Calendar c = Calendar.getInstance(); Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime()); String formattedDate = df.format(c.getTime());
ref.child("time").setValue(formattedDate); ref.child("time").setValue(formattedDate);
ref.child("bus_id").setValue(bus_id);
ref.child("destination").setValue(destination); ref.child("destination").setValue(destination);
ref.child("start_busstop_id").setValue(start_busstop_id);
ref.child("stop_busstop_id").setValue(stop_busstop_id);
// Date currentTime = Calendar.getInstance().getTime(); // Date currentTime = Calendar.getInstance().getTime();
// Log.d(TAG, "Location: " + location.getLatitude() + " " + location.getLongitude()+" "+location.getTime()+" "+currentTime); // Log.d(TAG, "Location: " + location.getLatitude() + " " + location.getLongitude()+" "+location.getTime()+" "+currentTime);
} }
};
}
;
}; };
public void addAllBusStop() {
DatabaseReference ref2 = FirebaseDatabase.getInstance().getReference("active_bus/" + user_id + "/busstop");
ref2.removeValue();
for (int i = 0; i < bus_stop.length; i++) {
final String path = "active_bus/" + user_id + "/busstop/" + i + "/" + bus_stop[i];
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(path);
ref.child("on_busstop_status").setValue(false);
ref.child("path_status").setValue(false);
//if path status is true that mean bus pass this path
}
}
@Override @Override
public void onConnected(@Nullable Bundle bundle) { public void onConnected(@Nullable Bundle bundle) {
requestLocationUpdates(); requestLocationUpdates();
Log.d(TAG, "Google Api Client Connected");
isMonitoring = true;
// startGeofencing();
} }
@Override @Override
...@@ -127,5 +361,7 @@ public class TrackerService3 extends Service implements ...@@ -127,5 +361,7 @@ public class TrackerService3 extends Service implements
@Override @Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
isMonitoring = false;
} }
} }
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/white</item>
<item name="colorPrimaryDark">@color/white</item>
<item name="android:windowLightStatusBar">true</item>
<!--<item name="android:windowTranslucentStatus">true</item>-->
<!--<item name="android:windowTranslucentNavigation">true</item>-->
</style>
</resources>
\ No newline at end of file
...@@ -41,4 +41,41 @@ ...@@ -41,4 +41,41 @@
<string name="firebase_password" translatable="false">password</string> <string name="firebase_password" translatable="false">password</string>
<!--Geofence-->
<!-- Buttons strings -->
<string name="add_geofences">Add geofences</string>
<string name="remove_geofences">Remove geofences</string>
<string name="geofences_added">Geofences added</string>
<string name="geofences_removed">Geofences removed</string>
<!-- Error strings -->
<string name="geofence_not_available">Geofence service is not available now</string>
<string name="geofence_too_many_geofences">Your app has registered too many geofences</string>
<string name="geofence_too_many_pending_intents">
You have provided too many PendingIntents to the addGeofences() call
</string>
<string name="unknown_geofence_error">
Unknown error: the Geofence service is not available now
</string>
<string name="geofence_transition_invalid_type">
Geofence transition error: invalid transition type %1$d
</string>
<!-- Transition type strings -->
<string name="geofence_transition_entered">Entered</string>
<string name="geofence_transition_exited">Exited</string>
<string name="unknown_geofence_transition">Unknown Transition</string>
<string name="geofence_transition_notification_text">
Click notification to return to app
</string>
<string name="insufficient_permissions">Insufficient permissions.</string>
<string name="permission_rationale">Location permission is needed for core functionality</string>
<string name="permission_denied_explanation">Permission was denied, but is needed for core
functionality.</string>
<string name="settings">Settings</string>
</resources> </resources>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment