从服务的Andr​​oid更新活动的用户界面用户界面、Andr、oid

由网友(;腥風持枪者-┈→)分享简介:我有被检查新任务的全部时间的服务。如果有新的任务,我想刷新活动的用户界面,显示该信息。我的确发现https://github.com/commonsguy/cw-andtutorials/tree/master/18-LocalService/这个例子。这是一个好approch?任何其他的例子吗?I have a...

我有被检查新任务的全部时间的服务。如果有新的任务,我想刷新活动的用户界面,显示该信息。 我的确发现https://github.com/commonsguy/cw-andtutorials/tree/master/18-LocalService/这个例子。这是一个好approch?任何其他的例子吗?

I have a service which is checking for new task all the time. If there is new task, I want to refresh the activity UI to show that info. I did find https://github.com/commonsguy/cw-andtutorials/tree/master/18-LocalService/ this example. Is that a good approch ? Any other examples?

感谢。

推荐答案

在您的服务:(使用COPA如下面的例子中服务)

In your service: (using COPA as service in example below).

使用一个LocalBroadCastManager。在您服务的onCreate,成立了广播:

Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster:

broadcaster = LocalBroadcastManager.getInstance(this);

当你要通知一些用户界面:

When you want to notify the UI of something:

static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";

static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";

public void sendResult(String message) {
    Intent intent = new Intent(COPA_RESULT);
    if(message != null)
        intent.putExtra(COPA_MESSAGE, message);
    broadcaster.sendBroadcast(intent);
}

在活动:

上的onCreate创建一个监听器:

Create a listener on onCreate:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setContentView(R.layout.copa);
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String s = intent.getStringExtra(COPAService.COPA_MESSAGE);
            // do something here.
        }
    };
}

和在ONSTART注册:

and register it in onStart:

@Override
protected void onStart() {
    super.onStart();
    LocalBroadcastManager.getInstance(this).registerReceiver((receiver), 
        new IntentFilter(COPAService.COPA_RESULT)
    );
}

@Override
protected void onStop() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    super.onStop();
}
阅读全文

相关推荐

最新文章