Java Can';无法使用BroadcastReceiver接收位置更新

Java Can';无法使用BroadcastReceiver接收位置更新,java,android,location,google-play-services,google-api-client,Java,Android,Location,Google Play Services,Google Api Client,我正在尝试制作一个应用程序,以获得定期的位置更新,并使用http post将位置发送到Web服务 我面临的问题是无法在后台使用GoogleAppServices的定位服务。 我遵循了,但他使用的LocationClient现在已被弃用。我正在关注这篇文章的评论,但我仍然无法让它在后台运行。我已经能够使用GoogleApiServices和activity,它工作得很好,但在后台不起作用,因此我尝试制作一个服务和一个广播接收器 这是我的密码: LocationReceiver.java Backg

我正在尝试制作一个应用程序,以获得定期的位置更新,并使用http post将位置发送到Web服务

我面临的问题是无法在后台使用GoogleAppServices的定位服务。 我遵循了,但他使用的LocationClient现在已被弃用。我正在关注这篇文章的评论,但我仍然无法让它在后台运行。我已经能够使用GoogleApiServices和activity,它工作得很好,但在后台不起作用,因此我尝试制作一个服务和一个广播接收器

这是我的密码:

LocationReceiver.java

BackgroundLocationService.java

AndroidManifest.xml

<service android:name=".BackgroundLocationService"
    android:enabled="true"
    android:exported="true"/>
<receiver android:name="com.amt.trackertest.LocationReceiver">
    <intent-filter>
        <action android:name="com.amt.trackertest.BroadcastReceiver"/>
    </intent-filter>
</receiver>
我进入该服务并构建了GoogleAPI客户端,但它从未被调用


p.D.:我对Android开发并不陌生,我知道还有很长的路要走。

[解决]问题是我从来没有连接过GoogleAppClient,我以为它是在OnStartCom上完成的,在一个if子句中,但这个子句总是错误的,然后就再也没有连接过Api。

[解决]问题是我从来没有连接过GoogleAppClient,我以为它是在onStartComand上完成的,并且在if子句中完成的,但是这个子句总是false,那么Api就从来没有连接过

public class BackgroundLocationService extends Service implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

    IBinder mBinder = new LocalBinder();

    private static final String TAG = "BGLocationSvc";

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    // Flag that indicates if a request is underway.
    private boolean mInProgress;

    private Boolean servicesAvailable = false;
    private PowerManager.WakeLock mWakeLock;

    public class LocalBinder extends Binder {
        public BackgroundLocationService getServerInstance() {
            return BackgroundLocationService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("BGLocationSvc", "On Create");
        buildGoogleApiClient();
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);

    /*
    WakeLock is reference counted so we don't want to create multiple WakeLocks. So do a check before initializing and acquiring.
    This will fix the "java.lang.Exception: WakeLock finalized while still held: MyWakeLock" error that you may find.
    */
        if (this.mWakeLock == null) { //**Added this
            this.mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
        }

        if (!this.mWakeLock.isHeld()) { //**Added this
           this.mWakeLock.acquire();
        }

        if (!servicesAvailable || mInProgress)
            return START_STICKY;
        if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting() && !mInProgress) {
            appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Started", Constants.LOG_FILE);
            mInProgress = true;
            mGoogleApiClient.connect();
        }
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }



    public void appendLog(String text, String filename) {
        File logFile = new File(filename);
        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            //BufferedWriter for performance, true to set append to file flag
            BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
            buf.append(text);
            buf.newLine();
            buf.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        // Turn off the request flag
        this.mInProgress = false;
        if (this.servicesAvailable && this.mGoogleApiClient != null) {
            this.mGoogleApiClient.unregisterConnectionCallbacks(this);
            this.mGoogleApiClient.unregisterConnectionFailedListener(this);
            this.mGoogleApiClient.disconnect();
            // Destroy the current location client
            this.mGoogleApiClient = null;
        }
        // Display the connection status
        // Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ":
        // Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
        if (this.mWakeLock != null) {
            this.mWakeLock.release();
            this.mWakeLock = null;
        }
        super.onDestroy();
    }

    /*
     * Called by Location Services when the request to connect the
     * client finishes successfully. At this point, you can
     * request the current location or start periodic updates
     */
    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10);  // Update location every 30    second. 10 = 1 second

        IntentFilter filter = new     IntentFilter("com.amt.trackertest.BroadcastReceiver");

        LocationReceiver myReceiver = new LocationReceiver();
        registerReceiver(myReceiver, filter);

        Intent intent = new Intent(this, LocationReceiver.class);
        PendingIntent pendingIntent = PendingIntent
                .getBroadcast(this, 54321, intent,    PendingIntent.FLAG_CANCEL_CURRENT);
        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
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient,
            mLocationRequest, pendingIntent);

    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "GoogleApiClient connection has been suspend");
    }

    /*
     * Called by Location Services if the attempt to
     * Location Services fails.
     */
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(TAG, "GoogleApiClient connection has failed");
    }

    protected synchronized void buildGoogleApiClient() {
        Log.i(TAG, "Building GoogleApiClient");
        this.mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
}
<service android:name=".BackgroundLocationService"
    android:enabled="true"
    android:exported="true"/>
<receiver android:name="com.amt.trackertest.LocationReceiver">
    <intent-filter>
        <action android:name="com.amt.trackertest.BroadcastReceiver"/>
    </intent-filter>
</receiver>
Intent i = new Intent(v.getContext(), BackgroundLocationService.class);
i.putExtra("foo", "bar");
ComponentName service = v.getContext().startService(i);