在Android Fragment中的GoogleApiClient

3

我尝试自学Android。在我的应用中,我想使用fragment来显示谷歌地图,并且当用户打开我的应用时,我想通过使用GoogleApiClient获取当前位置。

我的fragment代码如下:

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

}

问题出在这里: - 在onConnected方法之前,onCreateView方法就已经出现了,因此我无法使用getLastLocation()获取位置信息,因为GoogleApiClient尚未连接。

我在谷歌上搜索了,但是我不知道如何解决。请帮帮我! 对我的英文表达表示抱歉。


尝试在片段的onCreate()方法中连接GoogleAPIClient。 - Jitesh Dalsaniya
我将“mMapView.getMapAsync”移动到onConnected中,它起作用了。无论如何,非常感谢。 - Nhật Trương
2个回答

1

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

第二个问题是我无法获取getLastLocation(),因为GoogleAPIClient尚未连接,因为FusedLocationApi仅维护后台,所以您需要在后台获取GoogleMap

请参见我的示例:https://gist.github.com/quydm/a458d908c4da2496672f83372304f417


0

在请求位置更新之前,您必须等待GoogleApiClient连接。为了实现这一点,您需要将此代码块(当前位于onCreateView()方法中)移动:

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

到被覆盖的方法 onConnected() 的主体中。 由于你遇到的问题,你不能直接在 onCreateView() 中使用此代码。在发送任何位置请求之前,必须先建立连接。连接可能会快速建立,也可能比正常情况下需要更长时间。这取决于许多你无法控制的因素。

因此,我建议显示某种进度条来指示位置服务正在连接,然后在调用 onConnected() 时删除进度条。当然,这完全取决于你的应用程序。如果位置服务对用户非常重要,则必须添加此功能;如果不是,则可能不需要添加。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接