Android Wear:无法将mainActivity强制转换为com.google.android.gms.location.LocationListener

时间:2017-01-26 00:19:12

标签: java android wear-os android-wear-2.0

我正在尝试使用示例here获取Android Wear 2.0设备的位置。我已导入:

com.google.android.gms.location.LocationListener
com.google.android.gms.location.LocationRequest
com.google.android.gms.location.LocationServices

但我收到错误:

01-26 00:08:24.508 15589-15589/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.buschecker.williamvenner.buschecker, PID: 15589
java.lang.ClassCastException: com.buschecker.williamvenner.buschecker.MainActivity$4 cannot be cast to com.google.android.gms.location.LocationListener
   at com.buschecker.williamvenner.buschecker.MainActivity.onConnected(MainActivity.java:166)
   at com.google.android.gms.common.internal.zzm.zzq(Unknown Source)
   at com.google.android.gms.internal.zzaal.zzo(Unknown Source)
   at com.google.android.gms.internal.zzaaj.zzvE(Unknown Source)
   at com.google.android.gms.internal.zzaaj.onConnected(Unknown Source)
   at com.google.android.gms.internal.zzaan.onConnected(Unknown Source)
   at com.google.android.gms.internal.zzzy.onConnected(Unknown Source)
   at com.google.android.gms.common.internal.zzl$1.onConnected(Unknown Source)
   at com.google.android.gms.common.internal.zzf$zzj.zzwZ(Unknown Source)
   at com.google.android.gms.common.internal.zzf$zza.zzc(Unknown Source)
   at com.google.android.gms.common.internal.zzf$zza.zzu(Unknown Source)
   at com.google.android.gms.common.internal.zzf$zze.zzxa(Unknown Source)
   at com.google.android.gms.common.internal.zzf$zzd.handleMessage(Unknown Source)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6119)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

我真的不知道该怎么做,我没有导入android.location.LocationServices,我正在导入com.google.android.gms.location.LocationServices因此我无法理解为什么我收到此错误谷歌搜索告诉我在两个库之间切换。

这是我的完整代码:

package com.buschecker.williamvenner.buschecker;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends WearableActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private String TransportAPI_ID  = "XXX";
    private String TransportAPI_Key = "XXX";

    private GoogleApiClient mGoogleApiClient;

    private ListView bus_stops;
    private ArrayAdapter<String> bus_stops_adapter;

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

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

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

        setContentView(R.layout.activity_main);
        setAmbientEnabled();

        bus_stops = (ListView)findViewById(R.id.bus_stop_list);

        String[] items = {"Loading..."};
        bus_stops_adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
        bus_stops.setAdapter(bus_stops_adapter);
        bus_stops.setClickable(true);
        bus_stops.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Object o = bus_stops.getItemAtPosition(position);

            }
        });
    }

    @Override
    public void onEnterAmbient(Bundle ambientDetails) {
        super.onEnterAmbient(ambientDetails);
        updateDisplay();
    }

    @Override
    public void onUpdateAmbient() {
        super.onUpdateAmbient();
        updateDisplay();
    }

    @Override
    public void onExitAmbient() {
        updateDisplay();
        super.onExitAmbient();
    }

    private void updateDisplay() {
        if (isAmbient()) {

        } else {

        }
    }

    /*private void updateLocation() {
        if (mLastLocation != null) {
            Log.println(Log.INFO,"Log","Got location successfully!");
            Log.println(Log.INFO, "LOG", bus_stops_adapter.toString());

            RequestQueue queue = Volley.newRequestQueue(this);
            String url = "http://transportapi.com/v3/uk/bus/stops/near.json?lat=" + mLastLocation.getLatitude() + "&lon=" + mLastLocation.getLongitude() + "&app_key=" + TransportAPI_Key + "&app_id=" + TransportAPI_ID;

            StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Log.println(Log.INFO, "Log", "SUCCESSFULLY GOT API THING");
                }

            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.println(Log.INFO, "Log", "FAILED??");
                }

            });
            queue.add(stringRequest);
        } else {
            Log.println(Log.INFO,"Log","Failed to get location!");
        }
    }*/

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},2542);
            return;
        }

        LocationRequest locationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(60)
                .setFastestInterval(30);

        LocationServices.FusedLocationApi
                .requestLocationUpdates(mGoogleApiClient, locationRequest, this)
                .setResultCallback(new ResultCallback() {

                    @Override
                    public void onResult(@NonNull Result result) {
                        if (result.getStatus().isSuccess()) {
                            Log.println(Log.INFO,"Log","It worked??");
                        } else {
                            Log.println(Log.INFO,"Log","It failed??");
                        }
                    }
                });
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi
                    .removeLocationUpdates(mGoogleApiClient, this);
        }
        mGoogleApiClient.disconnect();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.println(Log.INFO,"Log","Connection suspended");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.println(Log.INFO,"Log","Connection failed");
    }
}

1 个答案:

答案 0 :(得分:2)

您使用

requestLocationUpdates(mGoogleApiClient, locationRequest, this)

thisMainActivity。但是,per the documentation,第三个参数必须是LocationListenerMainActivity未实现。

您必须实现界面并覆盖onLocationChanged方法。

public class MainActivity extends WearableActivity implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

  @Override
  public void onLocationChanged (Location location) {
    // Do something with the location
  }

...
}