我想每隔30秒将用户的位置保存到android服务的firebase实时数据库,我的服务在我添加firebase时停止,没有崩溃日志,有什么建议吗?或实现这一目标的最佳解决方案感谢
public class LocationService extends Service {
double pLatitude, pLongitude;
private DatabaseReference mDatabase;
FirebaseUser user;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(),"Service Started", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
//service stops(crashes) on below two lines
mDatabase = FirebaseDatabase.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_LONG).show();
pushtofirebase(getLocation());
} catch (Exception e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 30000);
}
private void pushtofirebase(GPSTracker gps) {
pLatitude = gps.getLatitude();
pLongitude = gps.getLongitude();
mDatabase.child("location").child(user.getUid()).push().setValue(String.valueOf(pLatitude));
mDatabase.child("location").child(user.getUid()).setValue(pLongitude);
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
private GPSTracker getLocation() {
GPSTracker gps = new GPSTracker(getApplicationContext());
if (gps.canGetLocation()) {
Toast.makeText(getApplicationContext(), gps.getLongitude() + " " + gps.getLatitude(), Toast.LENGTH_SHORT).show();
} else {
gps.showSettingsAlert();
}
return gps;
}
}