关闭应用程序后如何在 Fragment 类中停止 AsyncTask?
MainActivity 类
public class MainActivity extends FragmentActivity {
}
BaseFragment 类由 Fragment 扩展
public class BaseFragment extends Fragment {
public MainActivity mActivity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (ChatActivity)this.getActivity();
}
public boolean onBackPressed(){
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
片段类
public class Fragment1 extends BaseFragment{
private Update task;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
toCallAsynchronous();
return inflater.inflate(R.layout.activity_online_korisnici, container,
false);
}
public void toCallAsynchronous() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
task =new Update();
// PerformBackgroundTask this class is the class that extends AsynchTask
task.execute("");
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 5000); //execute in every 50000 ms
}
private class Update extends AsyncTask<Object, Object, List<Object>>{
@Override
protected List<Object> doInBackground(Object... params) {
}
@Override
protected void onPostExecute(List<Object> result) {
}
}
}