0

我有一个调用服务的活动,该服务具有实现 locationListener 的内部类。该服务旨在获取用户的位置。一旦找到位置,它就会在应用程序对象中设置 lon/lat 值,调用活动可以从中检索它们。在 onLocationChanged 中,一旦我有了 lon/lat 值并设置它们,我就会调用 Service.StopSelf。该服务确实会根据日志记录停止,但不会返回到调用活动。此时在调用活动中,我尝试从应用程序对象中获取这些值以进一步处理它们。在调用活动中的 startService 之后没有执行任何代码。任何想法为什么。提前致谢。

[编辑] 在 app 对象中设置值

在调用活动中。

startService(new Intent(NfcscannerActivity.this, LocationService.class));


                double latitude = nfcscannerapplication.getLat();
                double longitude = nfcscannerapplication.getLon();

                Log.e(TAG, "got the geopoint from application object...." + latitude + " " + longitude);

服务。

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class LocationService extends Service{

    private static final String TAG = LocationService.class.getSimpleName();
    LocationManager mlocManager;
    LocationListener mlocListener;
    NfcScannerApplication nfcscannerapplication;


    @Override
    public void onCreate() {

        nfcscannerapplication = (NfcScannerApplication)getApplication();
        mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);   
        mlocListener = new MyLocationListener();

        Log.e(TAG, "Service created and location manager and listener created");
        super.onCreate();
    }



    @Override
    public void onDestroy() {
         mlocManager.removeUpdates(mlocListener);
         Log.e(TAG, "Service destroyed");
        super.onDestroy();
    }




    @Override
    public void onStart(Intent intent, int startId) {
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
         Log.e(TAG, "requesting location updates");
        super.onStart(intent, startId);
    }



    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }







    private class MyLocationListener implements LocationListener
    {

        @Override
        public void onLocationChanged(Location loc) {
            Log.e(TAG, "about to set geopoints in application object");
            nfcscannerapplication.setLat( loc.getLatitude());
            nfcscannerapplication.setLon(loc.getLongitude()); 
            String Text = "My current location is: " +"Latitude = " + loc.getLatitude() + "Longitude = " 
            + loc.getLongitude();             
            Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();

            LocationService.this.stopSelf();




        }



        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }


    }//end of MyLocationListener





}// end of service

应用程序对象。

public class NfcScannerApplication extends Application{

    private static final String TAG = NfcScannerApplication.class.getSimpleName();
    LoginValidate loginValidate;
    ValidateUser validateUser;
    LoginWebservice loginWebservice;
    DateTime globalDateTime;
    double lon;
    public double getLon() {
        return lon;
    }

    public void setLon(double lon) {
        Log.e(TAG, "inside setLon in app obj");
        this.lon = lon;
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        Log.e(TAG, "inside setLat in app obj");
        this.lat = lat;
    }

    double lat;
4

1 回答 1

1

首先创建一个自定义 Intent 对象来保存您的位置数据:

/**
 * 
 */
package com.example.test;

import android.content.Intent;

/**
 * @author formation1
 * 
 */
public class LocationChangeIntent extends Intent {
    private final double       lon;
    private final double       lal;

    public static final String ACTION_LOCATION_CHAHGE = "com.example.test.LocationChangeIntent";

    /**
     * @param aLon
     * @param aLal
     */
    public LocationChangeIntent(double aLon, double aLal) {
        super(ACTION_LOCATION_CHAHGE);
        lon = aLon;
        lal = aLal;
    }

    /**
     * @return the lal
     */
    public double getLaltitude() {
        return lal;
    }

    /**
     * @return the lon
     */
    public double getLongitude() {
        return lon;
    }

}

之后,您必须从服务中添加 sendBroadcast:

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class LocationService extends Service {

    private static final String TAG = LocationService.class.getSimpleName();
    LocationManager             mlocManager;
    LocationListener            mlocListener;
    NfcScannerApplication       nfcscannerapplication;

    @Override
    public void onCreate() {

        nfcscannerapplication = (NfcScannerApplication) getApplication();
        mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mlocListener = new MyLocationListener();

        Log.e(TAG, "Service created and location manager and listener created");
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        mlocManager.removeUpdates(mlocListener);
        Log.e(TAG, "Service destroyed");
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
        Log.e(TAG, "requesting location updates");
        super.onStart(intent, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    private class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {
            Log.e(TAG, "about to set geopoints in application object");
            nfcscannerapplication.setLat(loc.getLatitude());
            nfcscannerapplication.setLon(loc.getLongitude());
            String text = "My current location is: " + "Latitude = " + loc.getLatitude() + "Longitude = "
                + loc.getLongitude();
            Log.d(TAG, text);
            fireLocationChangeEvent(loc.getLongitude(), loc.getLatitude());

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

    }// end of MyLocationListener

    private void fireLocationChangeEvent(double lon, double lal) {
        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new LocationChangeIntent(lon, lal));
    }
}// end of service 

最后从您的活动中注册一个广播接收器。

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private BroadcastReceiver   locationChangereceiver;
    private double              lon;
    private double              lal;

    TextView                    text;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.text);

        locationChangereceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                LocationChangeIntent myIntent = (LocationChangeIntent) intent;
                lon = myIntent.getLongitude();
                lal = myIntent.getLaltitude();
                text.setText(String.format("Location Update/Read from Activity\n  long : %s lalt:  %s ", lon, lal));
                // stop the service.
                stopService(new Intent(context, LocationService.class));
            }
        };
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(locationChangereceiver,
                new IntentFilter(LocationChangeIntent.ACTION_LOCATION_CHAHGE));
        startService(new Intent(this, LocationService.class));

        // Log.e(TAG, "got the geopoint from application object...." + latitude
        // + " " + longitude);

    }

    /**
     * callback method from QuantityDialogFragment, returning the value of user
     * input.
     * 
     * @param selectedValue
     */
    public void onUserSelectValue(String selectedValue) {

        // TODO add your implementation.
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.support.v4.app.FragmentActivity#onDestroy()
     */
    @Override
    protected void onDestroy() {

        super.onDestroy();
        // if no update make sure to stop the servcie.
        stopService(new Intent(this, LocationService.class));
        LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(locationChangereceiver);
    }

}
于 2012-10-02T12:46:49.857 回答