【问题标题】:How do i notify the activity on service completion?如何在服务完成时通知活动?
【发布时间】:2011-07-15 06:32:37
【问题描述】:

我有一个名为 message.java 的活动,它绑定到 GPS.java 服务。从 GPS.java 获得的经纬度必须在 message.java 中使用。我们通过使用 servicebinder 在 onServiceConnected() 中获取纬度和经度的默认值。 这是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
              }

getLatitude() 和 getLongitude() 返回 GPS.java 中正确的纬度和经度。问题是上面显示的 lat 和 lon 打印默认值,所以当服务中的纬度和经度更新时,我希望 lat 和 lon 也应该更新(应该在服务更新时通知活动)

请提供代码以适当放置它们

【问题讨论】:

    标签: android service binding android-activity broadcastreceiver


    【解决方案1】:

    首先创建像MyLocationListener这样的接口,如下所示

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

    现在将GPS 类更新为

    public class GPS {
      ArrayList<MyLocationListener> listeners = new ArrayList<MyLocationListener>();
    
      public void addLocationListener(MyLocationListener listener) {
        listeners.add(listener);
      }
    }
    

    所以你改变纬度或经度的地方只需调用

    notifyChangeLocation(lat, lon);
    

    这个方法有如下代码:

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

    这是第一部分,现在第二件事是在您的活动中添加侦听器,方法是创建一个 MyServiceConnection 类,如下所示:

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

    现在只需注册监听器 gps.addLocationListener(mConnection);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 2020-03-08
      相关资源
      最近更新 更多