在StopSelf之后,android服务不返回调用活动

时间:2012-10-02 10:36:05

标签: android service location

我有一个活动,它调用一个具有实现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

Application对象。

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;

1 个答案:

答案 0 :(得分:1)

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

/**
 * 
 */
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 

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

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

}