Android - 从服务保存位置更新(使用LocationServices API)

时间:2015-08-05 16:45:15

标签: android service location broadcastreceiver google-maps-android-api-2

我已经设置了一个应用程序接收位置更新的环境,该环境可以处理onLocationChanged回调。

// Setup the client.
mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

// Register the location update.
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

// Interface callback. Called every 5 seconds.
@Override
public void onLocationChanged(Location location) {
    // Save the location coordinates to a file.
}

到目前为止一切顺利。然后,就我的目的而言,即使应用程序没有运行,我也看到需要触发onLocationChanged回调 - 这就是BroadcastReceivers和服务进入的地方。

我想要一个BroadcastReceiver来启动一个Service,这会保存位置坐标更新做一个文件。所以,在我看来,架构会像:

// Register the BroadcasReceiver to the activity.
registerReceiver(mBroadcastReceiver, new IntentFilter());

// The BroadcastReceiver
public static class MyBroadcastReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        MyActivity.myContext.startService(new Intent(context, MyService.class));
    }
}

// The Service class.
public static class MyService extends Service {
    private boolean isRunning  = false;

    @Override
    public void onCreate() {        
        isRunning = true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //Creating new thread for my service.
        //Always write your long running tasks in a separate thread, to avoid ANR
        new Thread(new Runnable() {
            @Override
            public void run() {
                    // Save location updates.
                }
                //Stop service once it finishes its task
                stopSelf();
            }
        }).start();
        return Service.START_STICKY;
    }

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

    @Override
    public void onDestroy() {
        isRunning = false;
    }
}

所有LocationServices API设置过程(下面的第一个代码块)都在活动onCreate方法内。

那么,如果应用未运行,我如何从服务创建的run()方法接收位置更新?整个设计应该像的是:

App not running/destroyed > A specific action trigger the Broadcasreceiver > The BroadcastReceiver trigger the Service > The Service trigger the location updates and save it to a file.

0 个答案:

没有答案