Android:从服务器获取数据到 activity

Android: Getting data from server to activity

我的应用程序在收到云消息通知后从服务器轮询数据。

GcmListenerService 中获取数据。我目前的方法是使用 Intent 通过广播接收器将数据传输到相关的 activity。这仅在 activity 位于前景时有效。

如何存储 GcmListenerService 获取的数据,以便 activity 在恢复时根据获取的数据更新自身?

您可以使用服务绑定。

将 Binder 实现声明为服务定义的一部分:

public class MyService extends Service {

    private final IBinder mBinder = new MyBinder();
    // Set this field whenever you receive data from the cloud.
    private ArrayList<MyDataType> latestCloudData;

    public class MyBinder extends Binder {
        public ArrayList<MyDataType> getLatestCloudData() {
            return MyService.this.latestCloudData;
        }
    }

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

通过提供 ServiceConnection 的实现,分别在您的 activity 的 onStartonStop 中绑定和取消绑定到您的服务:

public class MyActivity extends Activity {
    // Provides an interface for communicating with the service.
    MyBinder mMyBinder = null;
    boolean mBound = false;

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to service
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder binder) {
            // Successfully bound, cast the IBinder to a MyBinder.
            MyBinder myBinder = (MyBinder) binder;
            // Can now use the MyBinder instance to communicate with the service.
            MyActivity.this.mMyBinder = myBinder;
            mBound = true;
            // Use the MyBinder to get the latest cloud data from the service and update your view.
            ArrayList<MyDataType> cloudData = MyActivity.this.mMyBinder.getLatestCloudData();
            MyActivity.this.updateViewWithCloudData(cloudData);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

    private void updateViewWithCloudData(ArrayList<MyDataType> data) {
        // Use the data to update your view here...
    }
}

有关绑定服务的更多信息,请参阅 the Android Developer Guide(上面的示例是该示例的修改版本)。

另请注意,这只会在您的 activity 从背景移动到前景(或重新创建)时帮助您。如果您 想在 activity 处于前台时接收更新,您还应该执行您的 activity 应该收听的广播。但是,您不需要将云数据作为此广播的一部分进行捆绑。广播可以只是一个简单的通知,提示 activity 使用 MyBinder.getLatestCloudData().

查询服务以获取新数据