开发者

How do i notify the activity on service completion?

I have an activity called message.java which is bound to the service GPS.java. The latitude and longitude obtained from GPS.java has to be used in message.java. We are getting the default values of latitude and longitude in the onServiceConnected() by using servicebinder. Here is the code for message.java

`Intent i=new Intent(getApplicationContext(), GPS.class);
             bindService(i,mConnection,Context.BIND_AUTO_CREATE)




       private GPS servicebinder;
       ServiceConnection mConnection = new ServiceConnection() {
            public void onServiceConnected(ComponentName className, IBinder service) {
                servicebinder = ((GPS.MyBinder)service).getService();

                double lat=servicebinder.getlatitude();

                double lon=servicebinder.getlongitude();
                  tex.setText("\nlatitude: " + lat+ "\nlongitude: "
                        + lon);


              // do any extra setup that requires your Service
              }
开发者_JAVA技巧

getLatitude() and getLongitude() return the latitude and longitude found in GPS.java which is correct. The problem is the lat and lon shown above prints the default values, so when the latitude and longitude in the service is updated i want the lat and lon also should be updated (Activity should be notified on service updation)

Please give the code to place them appropriately


First Create the Interface like MyLocationListener as following

public interface MyLocationListener {
  public void locationChanged(double lat, double lon);
}

Now Update the GPS class as

public class GPS {
  ArrayList<MyLocationListener> listeners = new ArrayList<MyLocationListener>();

  public void addLocationListener(MyLocationListener listener) {
    listeners.add(listener);
  }
}

So Where you have changed the latitude or longitude just call the

notifyChangeLocation(lat, lon);

and this method has following code:

public void notifyChangeLocation(double lat, double lon) {
Iterator<MyLocationListener> itr = listeners.iterator();
  while(itr.hasNext()) {
    itr.next().locationChanged(lat, lon);
  }
}

This is the first part, now the second thing is to add the listener in your activity, by Making an class MyServiceConnection which is like:

public class MyServiceConnection implements ServiceConnection, MyLocationListener {
  //add the unimplemented methods
  public void locationChanged(double lat, double lon) {
    // do any extra setup that requires your Service
  }
}
ServiceConnection mConnection = new MyServiceConnection();
Intent i=new Intent(getApplicationContext(), GPS.class);
bindService(i,mConnection,Context.BIND_AUTO_CREATE);

Now just register the listener gps.addLocationListener(mConnection);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜