从 Activity 调用服务但在 logcat 中没有得到任何东西?

Service getting called from Activity but not getting anything in logcat?

这有点像转贴,对此我深表歉意,但上次发布时我以为我把它记下来了,但显然没有。当我尝试调用我用来获取此错误的服务时,原因是:java.lang.IllegalStateException: GoogleApiClient is not connected yet. 因为我什至在连接 GoogleApiClient 之前就试图调用 LocationServices。因此,在稍微更改代码后,我不再收到错误消息,实际上我不再收到 logcat 中的任何内容。 这就是我从 SearchActivity.class:

开始我的服务的方式

SearchActivity.class

 button = (Button)findViewById(R.id.buttonPressed);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startService(new Intent(getBaseContext(), LocationService.class));

        }
    });

这是服务:

LocationService.class

public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {

    // LogCat tag
    private static final String TAG = LocationService.class.getSimpleName();

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private Location mLastLocation;

    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;

    // boolean flag to toggle periodic location updates
    private boolean mRequestingLocationUpdates = false;

    private LocationRequest mLocationRequest;

    // Location updates intervals in sec
    private static int UPDATE_INTERVAL = 10000; // 10 sec
    private static int FATEST_INTERVAL = 5000; // 5 sec
    private static int DISPLACEMENT = 10; // 10 meters


    @Override
    public void onCreate() {
        super.onCreate();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (mGoogleApiClient != null) {
            if(mGoogleApiClient.isConnected()) {
                if (mLocationRequest != null) {
                    togglePeriodicLocationUpdates();
                }
            }
        }



        return START_NOT_STICKY;
    }

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

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    private void togglePeriodicLocationUpdates() {
        mGoogleApiClient.connect();
        if(mGoogleApiClient.isConnected()) {
            if (!mRequestingLocationUpdates) {

                mRequestingLocationUpdates = true;

                startLocationUpdates();

                Log.d(TAG, "Periodic location updates started!");

            } else {

                mRequestingLocationUpdates = false;

                // Stopping the location updates
                stopLocationUpdates();

                Log.d(TAG, "Periodic location updates stopped!");
            }
        }
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    protected void startLocationUpdates() {
        mGoogleApiClient.connect();
        if(mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnected(Bundle arg0) {
        createLocationRequest();
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

@Override
public void onLocationChanged(Location location) {
    // Assign the new location
    mLastLocation = location;

    Toast.makeText(getApplicationContext(), "Location changed!",
            Toast.LENGTH_SHORT).show();
}

@Override
public boolean stopService(Intent name) {
    return super.stopService(name);
}

AndroidManifest.xml

    </activity>
    <service android:name=".LocationService">
    </service>

编辑:

好吧,我想出了如何让它发挥作用。 但现在我面临的问题是必须点击按钮 2 次才能正常启动。只需稍微更改 onStartCommand()。

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
            if(mGoogleApiClient.isConnected()) {

                if (mLocationRequest != null) {

                    togglePeriodicLocationUpdates();
                }
            }
        }



        return START_NOT_STICKY;
    }

您应该阅读有关 GoogleApiClient 的文档,尤其是(对于手头的问题)connect() method。我已经突出显示了相关部分:

Connects the client to Google Play services. This method returns immediately, and connects to the service in the background. If the connection is successful, onConnected(Bundle) is called and enqueued items are executed. On a failure, onConnectionFailed(ConnectionResult) is called.

If the client is already connected or connecting, this method does nothing.

所以,这就是您的代码当前发生的情况:

  1. 您单击按钮启动服务。
  2. 您在 onCreate() 中创建了 GoogleApiClient。
  3. 您在 onStartCommand 中调用 connect(),return 会立即在后台进行连接。
  4. 您检查了 isConnected(),但是,由于连接仍在继续,您什么都不做,并且 return 来自 onStartCommand。
  5. 稍后,您单击按钮再次启动服务。
  6. 因为已经创建好了,所以直接进入onStartCommand。
  7. 至此,GoogleApiClient 已连接,因此其他一切都按预期工作。

你应该做的是实现onConnected()。从那里,调用 togglePeriodicLocationUpdates() 而不是在 onStartCommand() 中执行此操作。这将完成你想要的:

  1. 单击按钮启动服务。
  2. 服务在 onCreate() 中创建 GoogleApiClient。
  3. 服务在 onStartCommand() 中发起连接。
  4. 在未来的某个时间,建立连接并且服务从 onConnected() 调用 togglePeriodicLocationUpdates()。