[英]How to call AsyncTask from a service or better way for background updating
我正在開發應用程序,現在它會從Twitter提取數據並在按下按鈕時更新IU。 我想使它自動化,因此它將在后台每小時更新一次,並最終使它也從后台發送通知。
我可以使用帶有更新按鈕的AsyncTask進行調用,該按鈕可以訪問Twitter並更新UI線程中的文本和圖標。 我還有一項服務,可以通過復選框打開和關閉。 我可以從服務中調用我的AsyncTask並將其更新為自動更新,還是應該做別的事情?
這是我為Main精簡的代碼:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lastUpdate = (TextView) findViewById(R.id.lastUpdate);
//checkbox starts and stops service "TheService"
CheckBox checkBox = (CheckBox) findViewById(R.id.check_box);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
startService(new Intent(MainActivity.this, TheService.class));
}else{
stopService(new Intent(MainActivity.this, TheService.class));
}
}
});
}
//This function is called when button is clicked.
public void startTask(View view) {
myAsyncTask mTask = new myAsyncTask();
mTask.execute("abc", "10", "Hello world");
}
public class myAsyncTask extends AsyncTask<String, Integer, Void> {
@Override
protected Void doInBackground(String... arg) {
try {
//accesses twitter here
} catch (TwitterException te) {
System.exit(-1);
}
//New thread is created because this function can't update UI Thread.
runOnUiThread(new Thread() {
public void run() {
TextView lastUpdate = (TextView) findViewById(R.id.lastUpdate);
//change text and icons on screen here
lastUpdate.setText("Last updated: " + currentTime);
}
});
return null;
}
}
}
服務:
public class TheService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
}
最好使用服務內部的線程代替服務器請求或重復或修復間隔請求,並使用廣播接收器或LocalBroadcastManager並從服務或線程發送廣播以更新您的活動中的用戶界面,不要忘記在應用程序處於注冊狀態時注銷和注銷接收器在resume(),pause()或stop()狀態上,否則會泄漏。請記住服務不是后台線程。線程很簡單,您必須在服務內部為服務器請求創建線程。 通過搜索有關您的問題,您還可以找到更好的SO線程和教程。 希望你能理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.