如何每秒刷新一次视图

时间:2018-11-10 14:05:01

标签: android

我正在使用此应用程序-https://github.com/googlesamples/android-AppUsageStatistics。我是android的新手,我试图每秒钟刷新一次视图。现在,视图在onCreate()或onResume()中刷新。 我正在尝试使用此:

public class MainActivity extends AppCompatActivity implements UsageContract.View {

private ProgressBar progressBar;
private TextView permissionMessage;
private UsageContract.Presenter presenter;
private UsageStatAdapter adapter;
public static Context myContext;

private long getStartTime() {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    progressBar = (ProgressBar) findViewById(R.id.progress_bar);
    permissionMessage = (TextView) findViewById(R.id.grant_permission_message);

    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new UsageStatAdapter();
    recyclerView.setAdapter(adapter);

    permissionMessage.setOnClickListener(v -> openSettings());

    presenter = new UsagePresenter(this, this);
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {



                                    presenter.retrieveUsageStats();

                                    throw new RuntimeException(e);





                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    t.start();


}



private void openSettings() {
    startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
}

@Override
protected void onResume() {
    super.onResume();

    showProgressBar(true);
    presenter.retrieveUsageStats();
}

@Override
public void onUsageStatsRetrieved(List<UsageStatsWrapper> list) {
    showProgressBar(false);
    permissionMessage.setVisibility(GONE);
    adapter.setList(list);
}

@Override
public void onUserHasNoPermission() {
    showProgressBar(false);
    permissionMessage.setVisibility(VISIBLE);
}

private void showProgressBar(boolean show) {
    if (show) {
        progressBar.setVisibility(VISIBLE);
    } else {
        progressBar.setVisibility(GONE);
    }
}   }

但不起作用。我究竟做错了什么?为什么视图中没有刷新?有人有主意吗?

1 个答案:

答案 0 :(得分:0)

理想情况下,您的视图不会轮询演示者以获取更新,但是要继续这种方式,请尝试使用计时器来运行您的重复任务,例如:

private Timer updateTimer;

@Override
protected void onStart() {
    super.onStart();
    updateTimer = new Timer();
    updateTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            presenter.retrieveUsageStats();
        }
    }, 0, 1000);
}

@Override
protected void onStop() {
    super.onStop();
    if(updateTimer != null) {
        updateTimer.cancel();
        updateTimer = null;
    }
}