访问服务到活动Android的值

时间:2014-03-11 13:49:26

标签: android service broadcastreceiver

我有一项跟踪用户位置的服务,我不确定如何将其与我的活动进行互动。我需要能够访问第一个可用的纬度&经度值,如果有变化,任何人都可以给我任何提示。

我的服务:

    public class LocationService extends Service implements
    GooglePlayServicesClient.ConnectionCallbacks,
    GooglePlayServicesClient.OnConnectionFailedListener,
    LocationListener {

    public double latitude, longitude;
    IBinder mBinder = new LocalBinder();

    private LocationClient mLocationClient;
    private LocationRequest mLocationRequest;
    // Flag that indicates if a request is underway.
    private boolean mInProgress;

    private Boolean servicesAvailable = false;

    public class LocalBinder extends Binder {
    public LocationService getServerInstance() {
        return LocationService.this;
    }
    }

    @Override
    public void onCreate() {
       super.onCreate();


       mInProgress = false;
       // Create the LocationRequest object
       mLocationRequest = LocationRequest.create();
       // Use high accuracy
       mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
       // Set the update interval to 5 seconds
       mLocationRequest.setInterval(Constants.UPDATE_INTERVAL);
       // Set the fastest update interval to 1 second
       mLocationRequest.setFastestInterval(Constants.FASTEST_INTERVAL);

       servicesAvailable = servicesConnected();

       /*
        * Create a new location client, using the enclosing class to
        * handle callbacks.
        */
       mLocationClient = new LocationClient(this, this, this);


    }

    private boolean servicesConnected() {

       // Check that Google Play services is available
       int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

       // If Google Play services is available
       if (ConnectionResult.SUCCESS == resultCode) {

           return true;
       } else {

           return false;
       }
    }

    public int onStartCommand (Intent intent, int flags, int startId)
    {
       super.onStartCommand(intent, flags, startId);

       if(!servicesAvailable || mLocationClient.isConnected() || mInProgress)
        return START_STICKY;

       setUpLocationClientIfNeeded();
       if(!mLocationClient.isConnected() || !mLocationClient.isConnecting() && !mInProgress)
       {
        appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Started", Constants.LOG_FILE);
        mInProgress = true;
        mLocationClient.connect();
       }

       return START_STICKY;
    }

    /*
    * Create a new location client, using the enclosing class to
    * handle callbacks.
    */
    private void setUpLocationClientIfNeeded()
    {
    if(mLocationClient == null) 
           mLocationClient = new LocationClient(this, this, this);
    }

    // Define the callback method that receives location updates
    @Override
    public void onLocationChanged(android.location.Location location) {
       // Report to the UI that the location was updated
       String msg = Double.toString(location.getLatitude()) + "," +
               Double.toString(location.getLongitude());
       Log.d("debug", msg);
       latitude = location.getLatitude();
       longitude = location.getLongitude();
       // Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
       appendLog(msg, Constants.LOCATION_FILE);

    }

    @Override
    public IBinder onBind(Intent intent) {
    return mBinder;
    }

    public String getTime() {
    SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return mDateFormat.format(new Date());
    }

    public void appendLog(String text, String filename)
    {       
      File logFile = new File(filename);
      if (!logFile.exists())
      {
         try
         {
            logFile.createNewFile();
         } 
         catch (IOException e)
         {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
      }
      try
      {
         //BufferedWriter for performance, true to set append to file flag
         BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
         buf.append(text);
         buf.newLine();
         buf.close();
      }
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
    }

    @Override
    public void onDestroy(){
       // Turn off the request flag
       mInProgress = false;
       if(servicesAvailable && mLocationClient != null) {
            mLocationClient.removeLocationUpdates(this);
            // Destroy the current location client
            mLocationClient = null;
       }
       // Display the connection status
       // Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
       appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Stopped", Constants.LOG_FILE);
       super.onDestroy();  
    }

    /*
    * Called by Location Services when the request to connect the
    * client finishes successfully. At this point, you can
    * request the current location or start periodic updates
    */
    @Override
    public void onConnected(Bundle bundle) {

       // Request location updates using static settings
       mLocationClient.requestLocationUpdates(mLocationRequest, this);
       appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Connected", Constants.LOG_FILE);
    }


    /*
    * Called by Location Services if the connection to the
    * location client drops because of an error.
    */
    @Override
    public void onDisconnected() {
       // Turn off the request flag
       mInProgress = false;
       // Destroy the current location client
       mLocationClient = null;
       // Display the connection status
       // Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
       appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected", Constants.LOG_FILE);
    }

    /*
    * Called by Location Services if the attempt to
    * Location Services fails.
    */
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    mInProgress = false;

       /*
        * Google Play services can resolve some errors it detects.
        * If the error has a resolution, try sending an Intent to
        * start a Google Play services activity that can resolve
        * error.
        */
       if (connectionResult.hasResolution()) {

       // If no resolution is available, display an error dialog
       } else {

       }
    }   

    }

我的广播接收器:

public class LocationLoggerServiceManager extends BroadcastReceiver {


        public static final String TAG = "LocationLoggerServiceManager";
        @Override
        public void onReceive(Context context, Intent intent) {
            // Make sure we are getting the right intent
            if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {

                    ComponentName comp = new ComponentName(context.getPackageName(), LocationService.class.getName());
                    ComponentName service = context.startService(new Intent().setComponent(comp));

                    if (null == service){
                        // something really wrong here
                        Log.e(TAG, "Could not start service " + comp.toString());
                    }
                }else {
                Log.e(TAG, "Received unexpected intent " + intent.toString());   
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

在onLocationChanged回调中,您需要使用 sendBroadcast 来通知您的活动更改。以下是另一个问题答案的示例(摘自https://stackoverflow.com/a/4739898/826731)。

在您的服务中,您可以像这样广播您的意图: sendBroadcast(new Intent(RefreshTask.REFRESH_DATA_INTENT));

RefreshTask.REFRESH_DATA_INTENT 变量只是一个字符串)

在您的活动中,您需要检查该特定字符串:

private class DataUpdateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(RefreshTask.REFRESH_DATA_INTENT)) {
        //Do stuff - maybe update my view based on the changed DB contents
    }
}

您可以按如下方式将值从服务传递到BroadcastReceiver:

在服务中

i.putExtra(“Counter”,counter);

在BroadcastReceiver中

intent.getIntExtra(“Counter”,-1); // -1是默认值