繁体   English   中英

如何为Android上的各种活动提供位置服务

[英]How to supply location services to diffent activities on Android

我目前正在开发一个Android应用,并且是该领域的新手。 我要执行以下操作:

创建一个封装必需功能的类,以使活动知道用户的位置并向该活动传递地图

这应该完成以下任务:

我有一个连接到定位服务以获取信息的类,其他活动可以使用该类来获取地图(片段)以及其他信息(经纬度等)以用于编程用途。

我无法弄清楚...我不希望自己将自己的东西用于Activity,但是Play服务的整个Google Location API似乎都依赖于它是FragmentActivity(无论如何)

有任何想法吗?

PS:我需要保持对2.3.3的支持

UPDATE我实现了扩展SupportMapFragment的类(缩短了),但是我在处理GMS的错误时遇到了麻烦。 在我的Galaxy Note 3上可以正常工作,但模拟器具有较旧的GMS版本(由于当前糟糕的错误处理),最终导致NullPointer异常:

public class LocationFragment extends SupportMapFragment implements GooglePlayServicesClient.ConnectionCallbacks, 
GooglePlayServicesClient.OnConnectionFailedListener, 
LocationListener {

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.map_fragment, container, false);

        initilizeMap();
        configureLocationClient();

        locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

        // Start with updates turned off
        updatesRequested = false;
        map.getUiSettings().setMyLocationButtonEnabled(true);

        locationClient = new LocationClient(activity.getBaseContext(), this, this);

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = getActivity();

        checkGooglePlayServices();
    }

private boolean checkGooglePlayServices() {
        // Check that Google Play services is available
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity.getBaseContext());
        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) {
            // In debug mode, log the status
            Log.d(TAG + ".servicesConnected()", "Google Play services is available.");
            // Continue
            return true;
        // Google Play services was not available for some reason
        } else {
            Log.d(TAG + ".servicesConnected()", "Google Play services is unavailable or outdated: " + resultCode);
            // Get the error dialog from Google Play services
            try {
                GooglePlayServicesUtil.getErrorDialog(resultCode, activity, CONNECTION_FAILURE_RESOLUTION_REQUEST).show();
            } catch (Exception e) {
                Log.e("Error: GooglePlayServiceUtil: ", "" + e);
            }
            /**
            Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, activity, CONNECTION_FAILURE_RESOLUTION_REQUEST);

            // If Google Play services can provide an error dialog
            if (errorDialog != null) {
                // Create a new DialogFragment for the error dialog
                ErrorDialogFragment errorFragment = new ErrorDialogFragment();
                // Set the dialog in the DialogFragment
                errorFragment.setDialog(errorDialog);
                // Show the error dialog in the DialogFragment
                errorFragment.show(activity.getSupportFragmentManager(),"Location Updates");
            }*/

            return false;
        }
    }

相应的活动是:

public class LocationTest extends FragmentActivity implements LocationListener {
    private static final String TAG = LocationTest.class.getSimpleName();

    private int count = 0;

    private TextView lat;
    private TextView lng;
    private TextView quality;
    private TextView conState;
    private TextView refreshCount;
    private TextView distance;
    private LocationFragment locFrag;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.locationtest);

        FragmentManager fManager = getSupportFragmentManager();
        locFrag = new LocationFragment();
        FragmentTransaction ft = fManager.beginTransaction();
        ft.replace(R.id.map, locFrag);
        ft.addToBackStack(null);
        ft.commit();

        locFrag.setGoal(Double.valueOf(8.83749747285), Double.valueOf(53.0663656578));

        lat = (TextView) findViewById(R.id.curLat);
        lng = (TextView) findViewById(R.id.curLng);
        quality = (TextView) findViewById(R.id.curQuality);
        conState = (TextView) findViewById(R.id.conState);
        refreshCount = (TextView) findViewById(R.id.count);
        distance = (TextView) findViewById(R.id.distance);
    }

    public void refreshLocation(View v) {
        locFrag.refreshLocation(v);
    }
    public void toggleUpdates(View v) {
        locFrag.toggleUpdates(v);

    }

    public void onLocationChanged(Location location)  {
        // Let the location parent know about the location change
//      super.onLocationChanged(location);
        count++;
        lat.setText(Double.toString(locFrag.getCurrentLatitude()));
        lng.setText(Double.toString(locFrag.getCurrentLongitude())); 
        quality.setText(Float.toString(locFrag.getAccuracy()));
        conState.setText(Boolean.toString(locFrag.isConnected()));
        refreshCount.setText(Integer.toString(count));
        distance.setText(Float.toString(locFrag.getDistance()));
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart()");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause()");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop()");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume()");
    }
}

我想知道是否有可能获得Google建议的ErrorDialog来从该SupportMapFragment进行处理,以便能够处理错误,或者停止该片段的膨胀并返回上一个活动

任何帮助表示赞赏:)

在捕获位置的当前类中使用此代码

currentLocation是位置对象

Intent intent = new Intent(this,target.class)
Bundle b = new Bundle();
b.putParcelable("Location", currentLocation);
i.putExtra("Location", b);
startActivity(i);

接收活动代码:

b = getArguments();
Location location = b.getParcelable("Location");

通过这种方式,您可以通过位置。我认为这可能对您有用。

暂无
暂无

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

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