如何为Android上的不同活动提供位置服务

时间:2013-11-19 13:11:01

标签: android location

我目前正在开发一款Android应用,而且我是该领域的新手。 我想做以下事情:

创建一个类,该类封装了所需的功能,让活动知道用户位置并将地图传递给活动

这应该完成以下任务:

我有一个连接到位置服务的类来获取信息,其他活动可以使用这个类来获取地图(片段)以及其他信息(lat long等)以供程序化使用。

我无法弄明白......我不希望我的东西成为活动本身 但似乎Play服务的整个Google Location API依赖于它是FragmentActivity(无论是什么)

有什么想法吗?

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

更新 我实现了一个扩展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()");
    }
}

我想知道是否有可能获得谷歌建议的ErrorDialog从该SupportMapFragment工作以便能够处理错误或者停止片段的膨胀并返回到之前的活动

任何帮助表示赞赏:)

1 个答案:

答案 0 :(得分:0)

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

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

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