无法使用BroadcastReceiver接收位置更新

时间:2016-04-07 11:59:18

标签: java android location google-play-services google-api-client

我正在尝试创建一个应用来定期更新位置,并使用http post将该位置发送到网络服务。

我面临的问题是无法在后台使用GoogleApiServices的位置服务。 我跟着this code,但他使用了现在已弃用的LocationClient。我正在关注帖子的评论,但我仍然无法让它在后台运行。我已经能够使用GoogleApiServices和活动,它工作正常,但没有在后台工作,因此我尝试制作服务和BroadcastReceiver。

这是我的代码:

LocationReceiver.java

public class LocationReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("LocationReceiver", "Something Received");
    }
}

BackgroundLocationService.java

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();
    }
}

的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>

我开始这样的后台服务:

Intent i = new Intent(v.getContext(), BackgroundLocationService.class);
i.putExtra("foo", "bar");
ComponentName service = v.getContext().startService(i);

我进入服务并构建谷歌api客户端,但接收器从未被调用。

P.D。:我在Android开发方面几乎不陌生,我知道还有很长的路要走。

1 个答案:

答案 0 :(得分:0)

[解决]问题是我从未连接过GoogleApiClient,我认为它是在if子句内的onStartComand上完成的,但是这个子句总是假的,那么Api就不会被连接了。