Android 使用基本位置示例代码创建服务

Android 使用基本位置示例代码创建服务,android,service,gps,location,Android,Service,Gps,Location,我想在Android中做一项服务(后台操作),时不时地跟踪设备的位置,并将其存储在SharedReference上,或者在位置发生变化时将其发送到我的服务器。我是从和收到这个密码的 代码如下: public class MainActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener { protected static final String TAG =

我想在Android中做一项服务(后台操作),时不时地跟踪设备的位置,并将其存储在SharedReference上,或者在位置发生变化时将其发送到我的服务器。我是从和收到这个密码的

代码如下:

public class MainActivity extends AppCompatActivity implements
ConnectionCallbacks, OnConnectionFailedListener {

    protected static final String TAG = "MainActivity";

    /**
    * Provides the entry point to Google Play services.
    */
    protected GoogleApiClient mGoogleApiClient;

    /**
    * Represents a geographical location.
    */
    protected Location mLastLocation;

    protected String mLatitudeLabel;
    protected String mLongitudeLabel;
    protected TextView mLatitudeText;
    protected TextView mLongitudeText;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        mLatitudeLabel = getResources().getString(R.string.latitude_label);
        mLongitudeLabel = getResources().getString(R.string.longitude_label);
        mLatitudeText = (TextView) findViewById((R.id.latitude_text));
        mLongitudeText = (TextView) findViewById((R.id.longitude_text));

        buildGoogleApiClient();
    }

    /**
    * Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
    */
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(LocationServices.API)
        .build();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    /**
    * Runs when a GoogleApiClient object successfully connects.
    */
    @Override
    public void onConnected(Bundle connectionHint) {
        // Provides a simple way of getting a device's location and is well suited for
        // applications that do not require a fine-grained location and that do not need location
        // updates. Gets the best and most recent location currently available, which may be null
        // in rare cases when a location is not available.
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            Log.e("Location", "not null");
            makeUseOfNewLocation(mLastLocation);
            } else {
            Toast.makeText(this, R.string.no_location_detected, Toast.LENGTH_LONG).show();
            // should request new one
            // location should be enabled
            Log.i(TAG,
            "No location data previously acquired.. should request!");

            Toast.makeText(this,
            "Requesting location data ..",
            Toast.LENGTH_SHORT).show();

            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(5000);

            PendingResult<Status> result = LocationServices.FusedLocationApi
            .requestLocationUpdates(mGoogleApiClient,
            locationRequest,
            new LocationListener() {

                @Override
                public void onLocationChanged(Location location) {
                    Log.e("Location", "not null");
                    makeUseOfNewLocation(location);
                }
            });
            // TODO: use result to retrieve more info
            Toast.makeText(this, result.toString(),Toast.LENGTH_LONG);
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }


    @Override
    public void onConnectionSuspended(int cause) {
        // The connection to Google Play services was lost for some reason. We call connect() to
        // attempt to re-establish the connection.
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }
    private void makeUseOfNewLocation(Location location) {
        // do your stuff here
        mLatitudeText.setText(String.format("%s: %f", mLatitudeLabel,
        location.getLatitude()));
        mLongitudeText.setText(String.format("%s: %f", mLongitudeLabel,
        location.getLongitude()));
    }
}
public类MainActivity扩展了AppCompatActivity实现
ConnectionCallbacks,OnConnectionFailedListener{
受保护的静态最终字符串TAG=“MainActivity”;
/**
*提供Google Play服务的入口点。
*/
受保护的GoogleapClient MGoogleapClient;
/**
*表示地理位置。
*/
受保护位置;
受保护字符串mLatitudeLabel;
受保护的字符串标签;
受保护的文本视图mLatitudeText;
受保护的文本视图文本;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main_活动);
mLatitudeLabel=getResources().getString(R.string.latitude_标签);
MLONGITELABEL=getResources().getString(R.string.longitude_标签);
mLatitudeText=(TextView)findViewById((R.id.latitude_text));
MLONGITEXT=(TextView)findViewById((R.id.longitude_text));
buildGoogleAppClient();
}
/**
*生成GoogleAppClient。使用addApi()方法请求LocationServices API。
*/
受保护的同步无效BuildGoogleAppClient(){
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
}
@凌驾
受保护的void onStart(){
super.onStart();
mGoogleApiClient.connect();
}
@凌驾
受保护的void onStop(){
super.onStop();
if(mgoogleapClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
/**
*当GoogleAppClient对象成功连接时运行。
*/
@凌驾
未连接的公共无效(捆绑连接提示){
//提供获取设备位置的简单方法,非常适合
//不需要细粒度位置且不需要位置的应用程序
//更新。获取当前可用的最佳和最新位置,该位置可能为空
//在极少数情况下,位置不可用。
mLastLocation=LocationServices.FusedLocationApi.getLastLocation(mgoogleapClient);
如果(mLastLocation!=null){
Log.e(“位置”,“非空”);
使用新位置(mLastLocation);
}否则{
Toast.makeText(this,R.string.no_location,Toast.LENGTH_LONG).show();
//你应该申请新的
//应启用位置
Log.i(标签,
“以前未获取位置数据..应请求!”);
Toast.makeText(这个,
“正在请求位置数据…”,
吐司。长度(短)。show();
LocationRequest LocationRequest=LocationRequest.create();
locationRequest.setPriority(locationRequest.PRIORITY\u高精度);
位置请求设置间隔(5000);
Pendingreult结果=LocationServices.FusedLocationApi
.RequestLocationUpdate(mgoogleapClient,
位置请求,
新位置侦听器(){
@凌驾
已更改位置上的公共无效(位置){
Log.e(“位置”,“非空”);
使用新位置(位置);
}
});
//TODO:使用结果检索更多信息
Toast.makeText(this,result.toString(),Toast.LENGTH\u LONG);
}
}
@凌驾
连接失败的公共void(连接结果){
//请参阅javadoc for ConnectionResult,以查看在中可能返回的错误代码
//OnConnection失败。
Log.i(标记,“连接失败:ConnectionResult.getErrorCode()=”+result.getErrorCode());
}
@凌驾
连接上的公共无效已暂停(内部原因){
//由于某种原因,与Google Play服务的连接丢失。我们调用connect()以
//尝试重新建立连接。
Log.i(标签“连接暂停”);
mGoogleApiClient.connect();
}
私有void makeUseOfNewLocation(位置){
//在这里做你的事
mLatitudeText.setText(String.format(“%s:%f”),mLatitudeLabel,
location.getLatitude());
MLONGITEXT.setText(String.format(“%s:%f”),MLONGITETEXT标签,
location.getLongitude());
}
}

我的问题是,通过在这个类上扩展服务,这个代码可以成为一个服务吗。如果这能起作用,并且能够时不时地在后台跟踪设备的位置

根据谷歌的文档,您需要在onConnected中使用Pending帐篷,以确保即使应用程序不在屏幕上,您也能运行后台服务

公共摘要PendingResult RequestLocationUpdate(GoogleAppClient、LocationRequest请求、PendingEvent callbackIntent) 使用指定PendingEvent上的回调请求位置更新

此方法适用于后台用例,更具体地说,适用于接收位置更新,即使应用程序已被系统终止。为此,请为已启动的服务使用悬挂式帐篷。对于前台用例,建议使用LocationListener版本的方法,请参阅requestLocationUpdates(GoogleAppClient、LocationRequest、LocationListener)

我前面的方法是创建一个包含在PendingEvent中的意图,然后在意图中指示从当前活动传递到处理程序类。在处理程序类中,哪个ext