简体   繁体   English

服务从活动中被调用,但在logcat中什么都没有得到?

[英]Service getting called from Activity but not getting anything in logcat?

This is kinda a repost and I'm sorry for that, but the last time I posted it I thought I got it down but apparently not. 这有点像是重新发布,对此我感到抱歉,但是上次发布时我以为我记下来了,但显然没有。 When I tried to call the Service I use to get this error Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet. 当我尝试调用服务时,我用来获取此错误的原因: java.lang.IllegalStateException: GoogleApiClient is not connected yet. Because I was trying to call LocationServices before GoogleApiClient was even connected. 因为我试图在GoogleApiClient尚未连接之前就调用LocationServices。 So after changing the code up a bit I wasn't getting the error anymore, in fact I wasn't getting anything in logcat anymore. 因此,在稍微修改一下代码之后,我再也不会收到错误了,实际上我再也没有在logcat中得到任何东西了。 This is how I start my Service from SearchActivity.class: 这是我从SearchActivity.class启动服务的方式:

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

        }
    });

This is the Service: 这是服务:

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 AndroidManifest.xml中

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

Edit: 编辑:

Well I figured how to get it working. 好吧,我想出了如何使它工作。 But now I'm facing the problem of having to click the button 2 times before it would start normally. 但是现在我面临的问题是必须单击两次按钮才能正常启动。 Only had to change the onStartCommand() a bit. 只需更改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;
    }

You should read the documentation on GoogleApiClient, particularly (for the question at hand) the connect() method . 您应该阅读GoogleApiClient上的文档,尤其是(针对当前问题) connect()方法 I've highlighted the relevant portion: 我强调了相关部分:

Connects the client to Google Play services. 将客户端连接到Google Play服务。 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. 如果连接成功,则调用onConnected(Bundle)并执行排队的项目。 On a failure, onConnectionFailed(ConnectionResult) is called. 失败时,将调用onConnectionFailed(ConnectionResult)。

If the client is already connected or connecting, this method does nothing. 如果客户端已经连接或正在连接,则此方法不执行任何操作。

So, this is what currently happens with your code: 因此,这是您的代码当前发生的情况:

  1. You click the button to launch the service. 您单击按钮以启动服务。
  2. You create the GoogleApiClient in onCreate(). 您可以在onCreate()中创建GoogleApiClient。
  3. You call connect() in onStartCommand which returns immediately while connection goes on in the background. 您可以在onStartCommand中调用connect(),当连接在后台继续进行时,该函数会立即返回。
  4. You check isConnected(), however, since connection is still going on, you do nothing and return from onStartCommand. 您检查isConnected(),但是,由于连接仍在进行中,因此您什么也不做,并从onStartCommand返回。
  5. Later, you click the button the launch the service again. 稍后,您单击按钮再次启动服务。
  6. As it has already been created, it goes directly to onStartCommand. 由于已经创建了它,因此它直接进入onStartCommand。
  7. By this point, the GoogleApiClient has connected, so everything else works as expected. 至此,GoogleApiClient已连接,因此其他所有功能均按预期工作。

What you should do is implement onConnected(). 您应该执行的是onConnected()。 From there, call togglePeriodicLocationUpdates() instead of doing that in onStartCommand(). 从那里,调用togglePeriodicLocationUpdates()而不是在onStartCommand()中进行。 This will accomplish what you want: 这将完成您想要的:

  1. Click button to launch service. 单击按钮启动服务。
  2. Service creates GoogleApiClient in onCreate(). 服务在onCreate()中创建GoogleApiClient。
  3. Service initiates connection in onStartCommand(). 服务在onStartCommand()中启动连接。
  4. Sometime in the future, the connection is established and service calls togglePeriodicLocationUpdates() from onConnected(). 在将来的某个时间,将建立连接,并且服务会从onConnected()调用togglePeriodicLocationUpdates()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM