首页 文章

从Android服务将数据保存到firebase实时数据库

提问于
浏览
0

我想每隔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;
    }
}

2 回答

  • 0

    它可能是本机崩溃,将logcat崩溃级别更改为详细,并将应用程序更改为无过滤器
    enter image description here

  • 0

    移动代码以将位置添加到mDatabase.addValueEventListener内的数据库应解决此问题 .

相关问题