我无法在内容Firebase连接Android的后台运行服务

时间:2018-03-20 09:32:42

标签: android firebase firebase-realtime-database

我想使用服务将用户位置发送到firebase RD,即使我的应用已关闭 我使用下面的代码,我尝试做所有事情,但不知道问题在哪里

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.HashMap;

import my.penta.xxx.xxx.activity.User;
import my.penta.xxx.xxx.helper.SQLiteHandler;

MyServiceGPS 

    public class MyServiceGPS extends Service {
        private static final String TAG = "GPSTEST";
        private LocationManager mLocationManager = null;
        private static final int LOCATION_INTERVAL = 1000;
        private static final float LOCATION_DISTANCE = 10f;
        FirebaseDatabase database;
        DatabaseReference myRef;
        private SQLiteHandler db;
        String SupDriver = "SupDriver",Driverr="provider",tags,Organization="Organization",Individual="Individual",maindriverid;
        String uid,email;
        Double latitudeLocation;
        Double longitudeLocation;

        private class LocationListener implements android.location.LocationListener
        {
            Location mLastLocation;

            public LocationListener(String provider)
            {
                Log.e(TAG, "LocationListener " + provider);
                mLastLocation = new Location(provider);
            }

            @Override
            public void onLocationChanged(Location location)
            {
                Log.e(TAG, "onLocationChanged: " + location);
                mLastLocation.set(location);

                latitudeLocation = location.getLatitude();
                longitudeLocation = location.getLongitude();

                LatLng p1 = new LatLng(latitudeLocation, longitudeLocation);

                if (tags.equals(SupDriver))
                {

                 String   MainProvideridtosend = maindriverid;
                String    SupProvideridtosend = uid;

                  String  Status = "3";
                   String  TypeOfxxx = "0";





                    writeNewUser(MainProvideridtosend, Double.toString(latitudeLocation), Double.toString(longitudeLocation), Status, TypeOfxxx,SupProvideridtosend);





                }else             {




                }
            }

            @Override
            public void onProviderDisabled(String provider)
            {
                Log.e(TAG, "onProviderDisabled: " + provider);
            }

            @Override
            public void onProviderEnabled(String provider)
            {
                Log.e(TAG, "onProviderEnabled: " + provider);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras)
            {
                Log.e(TAG, "onStatusChanged: " + provider);
            }
        }

        LocationListener[] mLocationListeners = new LocationListener[] {
                new LocationListener(LocationManager.GPS_PROVIDER),
                new LocationListener(LocationManager.NETWORK_PROVIDER)
        };

        @Override
        public IBinder onBind(Intent arg0)
        {
            return null;
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId)
        {
            Log.e(TAG, "onStartCommand");
            super.onStartCommand(intent, flags, startId);
            return START_STICKY;
        }

        @Override
        public void onCreate()
        {
            Log.e(TAG, "onCreate");

            //chek if sup Driver or Driver
            db = new SQLiteHandler(getApplicationContext());

            HashMap<String, String> usertag = db.getUserTag();

            tags = usertag.get("tag");

            db = new SQLiteHandler(getApplicationContext());

            HashMap<String, String> user = db.getProviderDetails();

            String name = user.get("name");
            email = user.get("email");
            String number = user.get("number");
             maindriverid = user.get("service"); // << supdriver is mainuserid, Driver is AcountType
            uid = user.get("uid");
            initializeLocationManager();
            try {
                mLocationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                        mLocationListeners[1]);
            } catch (java.lang.SecurityException ex) {
                Log.i(TAG, "fail to request location update, ignore", ex);
            } catch (IllegalArgumentException ex) {
                Log.d(TAG, "network provider does not exist, " + ex.getMessage());
            }
            try {
                mLocationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                        mLocationListeners[0]);
            } catch (java.lang.SecurityException ex) {
                Log.i(TAG, "fail to request location update, ignore", ex);
            } catch (IllegalArgumentException ex) {
                Log.d(TAG, "gps provider does not exist " + ex.getMessage());
            }
        }

        @Override
        public void onDestroy()
        {
            Log.e(TAG, "onDestroy");
            super.onDestroy();
            if (mLocationManager != null) {
                for (int i = 0; i < mLocationListeners.length; i++) {
                    try {
                        mLocationManager.removeUpdates(mLocationListeners[i]);
                    } catch (Exception ex) {
                        Log.i(TAG, "fail to remove location listners, ignore", ex);
                    }
                }
            }
        }

        private void initializeLocationManager() {
            Log.e(TAG, "initializeLocationManager");
            if (mLocationManager == null) {
                mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
            }
        }

        private void writeNewUser(String uidl, String lat, String longit,String statuss,String typeOfxxx,String SupProviderid) {
            User user = new User(uidl, lat,longit,statuss,typeOfxxx,SupProviderid);

            database = FirebaseDatabase.getInstance();
            myRef = database.getReference("xxx");

            String emailencod = email.replace(".", ",");

            myRef.child(emailencod).setValue(user);
        }
    }

当我以这种方式启动服务时

    Intent serviceIntent = new Intent(Pop_SupDriverOrder.this, MyServiceGPS.class);
                    startService(serviceIntent);

//open google map for direction 
               double lat = Double.parseDouble(latitudeLocationv);

                double lng = Double.parseDouble(longitudeLocationv);

                String format = "geo:0,0?q=" + lat + "," + lng + "( Location title)";

                Uri uri = Uri.parse(format);


                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);

的Manifest.xml

<service
            android:name=".Driver.MyServiceGPS"
            android:enabled="true"
            android:process=":my_service"
            android:exported="true"></service>

当此服务启动时,该应用将停止工作

错误日志

03-20 17:18:58.562 14670-15181/my.penta.dumpster.dumpster I/FirebaseCrash: Sending crashes
03-20 17:19:01.131 14670-14711/my.penta.dumpster.dumpster V/FA: Inactivity, disconnecting from the service
03-20 17:19:02.623 14670-14755/my.penta.dumpster.dumpster I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-20 17:19:02.624 14670-14755/my.penta.dumpster.dumpster I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-20 17:19:08.325 14670-14703/my.penta.dumpster.dumpster W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
03-20 17:22:48.867 14670-14758/my.penta.dumpster.dumpster D/TcpOptimizer: [my.penta.dumpster.dumpster] Full closed: sid=125, tcpi_state=8

请注意,如果我删除了firebase代码,它将正常工作

1 个答案:

答案 0 :(得分:0)

检查FusedLocationClient https://developer.android.com/training/location/receive-location-updates.html#java

如果您想在服务中接收位置,可以使用

mFusedLocationClient.requestLocationUpdates(createLocationRequest(), getLocationPendingIntent());


  /**
   * Build location request
   * @return {@link LocationRequest}
   */
  public static LocationRequest createLocationRequest() {
    return LocationRequest.create()
        .setSmallestDisplacement(SMALLEST_DISPLACEMENT)
        .setInterval(INTERVAL)
        .setMaxWaitTime(2 * INTERVAL)
        .setFastestInterval(INTERVAL)
        .setPriority(PRIORITY);
  }


  /**
   * Provide {@link PendingIntent} for background service
   * @return intent
   */
  private PendingIntent getLocationPendingIntent() {
      Intent intent = new Intent(context.getApplicationContext(), LocationIntentService.class);
return PendingIntent.getService(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
  }

意图服务:

/**
 * This {@link Service} monitors and reports {@link Location} 
 */
public class LocationIntentService extends IntentService {

  public LocationIntentService() {
    super(LocationIntentService.class.getName());
  }

  @Nullable @Override public IBinder onBind(final Intent intent) {
    return null;
  }

  @Override protected void onHandleIntent(@Nullable Intent intent) {
    if (LocationResult.hasResult(intent)) {
      Location location = LocationResult.extractResult(intent).getLastLocation();
      double latitude = location.getLatitude();
      double longitude = location.getLongitude();
    }
  }
}

不要忘记将服务添加到Android Manifest:

<service
        android:name=".location.LocationIntentService"
        android:exported="false"/>