android - 在不同的用户界面上,安卓做背景资料

  显示原文与译文双语对照的内容
67 1

我设计了一个应用程序来获取网络信息,每 5秒更新一次用户界面。建议在单独线程上执行背景进程,而不是UI线程,但是我还是得到了一个错误:

"i/choreographer﹕跳过 3730帧应用程序可以能在主线程上工作太多" !

为什么这是我的密码?

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 wifiTextView = (TextView)findViewById(R.id.wifi_textView);
 ipTextView = (TextView)findViewById(R.id.ip_val_textView);
//and so on
//Updating the UI every mInterval seconds, using a separate thread than UI thread
 Thread backgroundThread = new Thread() {
 @Override
 public void run() {
 try {
 while (!isInterrupted()) {
 Thread.sleep(mInterval);
 runOnUiThread(new Runnable() {
 @Override
 public void run() {
//Log.d(DEBUG_TAG,"run(): Background thread");
 MyNetwork network = new MyNetwork(getApplicationContext());//passing the context
 updateUI(network);
 }
 });
 }
 } catch (InterruptedException e) {
 wifiTextView.setText("Exception: Please Close and Restart the App");
 }
 }
 };
 backgroundThread.start();
}

在同一个MainActivity类中,我有一个 private 函数:

 private void updateUI(MyNetwork network){
//Handles updating the textviews in the UI
//Log.d(DEBUG_TAG,"updateUI(DeepstreamNetwork)");
 if (network.isConnected()){
 wifiTextView.setText(R.string.wifi_is_on);
 wifiTextView.setTextColor(Color.GREEN);
 ipTextView.setText(network.getIpAddress());
 else {
 wifiTextView.setText(R.string.wifi_is_off);
 wifiTextView.setTextColor(Color.RED);
 ipTextView.setText("N/A");
 }
}

更新

所以,我已经经更新了MainActivity类以使这里MyAsyncTask方法处理背景工作。"。"。这是我的代码:

private class MyAsyncTask extends AsyncTask<Void, Void, MyNetwork> {
 @Override
 protected void onPostExecute(MyNetwork network) {
 updateUI(network);
 }
 @Override
 protected MyNetwork doInBackground(Void... params) {
 MyNetwork network = new MyNetwork(getApplicationContext());//passing the context
 return network;
 }
 @Override
 protected void onProgressUpdate(Void... values) {
 super.onProgressUpdate(values);
 }
}

两个问题:

1 ) 我如何强制它每 5秒执行一次后台任务。由于网络状态每隔几秒更改一次,所以我希望它能分别更新 UI 。

2 ) 我应该在MainActivity中这样调用它?new MyAsyncTask().execute() ;

全部致谢

时间:原作者:0个回答

115 5

我不知道你为什么叫它Thread backgroundThread = new Thread()因为 runOnUiThread() 是主要的线索。

你应该在 asynctask 中尝试,在中只更新 onPostExecute() 中的UI

编辑:

private class MyAsyncTask extends AsyncTask<Void, Void, String> {
 private MyNetwork network;
 @Override
 protected void onPreExecute() {
 this.network = new MyNetwork(getApplicationContext()); 
 }
 @Override
 protected String doInBackground(Void... params) {
 return network.getIpAddress();
 }
 @Override
 protected void onPostExecute(String ipAddress) {
 if (this.network.isConnected()){
 wifiTextView.setText(R.string.wifi_is_on);
 wifiTextView.setTextColor(Color.GREEN);
 ipTextView.setText(ipAddress);
 else {
 wifiTextView.setText(R.string.wifi_is_off);
 wifiTextView.setTextColor(Color.RED);
 ipTextView.setText("N/A");
 }
 }
 @Override
 protected void onProgressUpdate(Void... values) {
 super.onProgressUpdate(values);
 }
}
原作者:
...