片段Android中的GoogleApiClient

时间:2016-10-20 15:54:16

标签: android fragment

我自己尝试学习Android。在我的应用程序中,我想使用片段显示谷歌地图,当用户打开我的应用程序时,我希望使用GoogleApiClient获取当前位置 我的片段代码:

public class HomeFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    public interface comuticateParent {
        public void sendMess(String text);
    }

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    comuticateParent callback;
    Button btn1;
    TextView textView;
    MapView mMapView;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    LocationRequest mLocationRequest;
    private GoogleMap googleMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        mMapView = (MapView) rootView.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume(); // needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        mMapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {
                googleMap = mMap;
                googleMap.setMyLocationEnabled(true);

                mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                Log.d("onCreateView", Boolean.toString(mGoogleApiClient.isConnected()));
                googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mylocation, 13));
            }
        });
        return rootView;
    }

    @Override
    public void onStart() {
        mGoogleApiClient.connect();
        Log.d("ConnectonStart", "Connected ");
        Log.d("ONstart", Boolean.toString(mGoogleApiClient.isConnected()));
        super.onStart();
    }

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

    @Override
    public void onResume() {
        mGoogleApiClient.connect();
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d("Connect", "Connected ");
        Log.d("onConnected", Boolean.toString(mGoogleApiClient.isConnected()));
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d("Connect", "failed ");
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity;
        if (context instanceof Activity) {
            activity = (Activity) context;
            callback = (comuticateParent) getActivity();
        }
    }

}

问题在这里: -Log in方法onCreateView出现在登录方法onconnected之前,所以我无法获得getLastLocation(),因为googleAPIClient还没有连接。

我在谷歌搜索但我不知道如何修复它。 请帮我! 抱歉,我的英语最好。

2 个答案:

答案 0 :(得分:1)

第一个问题登录方法onCreateView出现在登录方法onconnected 之前,因为GoogleApiClient将访问Google API,验证应用配置,验证证书指纹等。处理过程需要很长时间。为了避免阻塞UI线程,它将在另一个线程中执行并使用异步回调。

第二个问题我无法获取getLastLocation(),因为googleAPIClient尚未连接,因为FusedLocationApi只会维护背景,因此您需要获取{{1}在背景中。

请在此处查看我的示例:https://gist.github.com/quydm/a458d908c4da2496672f83372304f417

答案 1 :(得分:0)

您必须等到GoogleApiClient已连接,然后才能请求位置更新。为此,您需要移动此代码块(目前在onCreateView()方法中找到):

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.d("onCreateView", Boolean.toString(mGoogleApiClient.isConnected()));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mylocation, 13));

到被覆盖的方法onConnected()的主体。 由于您遇到的问题,您无法直接在onCreateView()中使用此代码。必须先建立连接,然后才能发送任何位置请求。连接可以快速建立或比正常时间更长。这取决于你控制之外的许多事情。

出于这个原因,我建议显示某种进度条以指示位置服务正在连接,然后在调用onConnected()时删除进度条。当然,这完全取决于您的应用。如果位置服务对于用户来说至关重要,那么这是必须的,如果没有,那么您可能不需要添加它。