保持SwipeRefreshLayout显示,直到服务运行完毕

时间:2016-01-11 23:48:56

标签: android

所以现在我在我的应用程序中刷卡刷新。激活后,将执行运行异步后台任务的服务。问题是,刷卡刷新指示灯立即消失。服务运行完成后如何保持显示(并更新我的回收站视图)? 这是一些代码:

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.StatusbarColor,R.color.Accent);

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                db = new DatabaseHelper(getApplicationContext());
                callRefreshService();

            }
        });

这是callRefreshService方法:

public void callRefreshService() {
        try{
            Intent service = new Intent(getApplicationContext(), UpdateScoresService.class);
            startService(service);
        }
        finally {
            list.clear();
            list.addAll(db.getTracked());
            db.closeDB();
            adapter.notifyDataSetChanged();
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

正如你所看到的,我尝试过使用try,但是这并没有帮助。

2 个答案:

答案 0 :(得分:1)

startService(Intent) does not block, it returns immediately.

You got two options:

  1. Ditch the Service for AsyncTask
  2. Allow the Service to communicate with your Activity

Choose 1 for something trivial like a one-off JSON download task. Call mSwipeRefreshLayout.setRefreshing(false) in the onPostExecute (Result result) block.

Choose 2 if you got something complex setup already. Communication between Activity and Service is slightly complicated, what you need is a 。如果你想要一些简单的东西,你可以看看事件总线,它可以很好地分离。

以下是事件总线的一些实现:

答案 1 :(得分:0)

在您的活动中创建BroadcastReceiver

BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // stop refreshing the layout
        mSwipeRefreshLayout.setRefreshing(false);
    }
};

将其注册到onResume()内的活动,以收听一些Intenet并在onPause()内取消注册

@Override
protected void onResume() {
    super.onResume();
    // register the receiver
    registerReceiver(receiver, new IntentFilter("com.example.app.STOP_REFRESH"));
}

@Override
protected void onPause() {
    super.onPause();
    // unregister the receiver
    unregisterReceiver(receiver);
}

然后在AsyncTask onPostExecute()内发送包含Intent

的邮件
Intent intent = new Intent("com.example.app.STOP_REFRESH");
// you can also add extras to this intent
// intent.putExtra("key", value);
sendBroadcast(intent);