仅在一个Android Activity中执行线程

时间:2014-06-05 19:52:33

标签: java android multithreading handler

我的Android项目中有三个java文件。两个是活动(MainActivityGeoActivity),一个是普通的java文件(PostHttp - >通过HTTP POST将数据发送到服务器)

我通过一个简单的按钮点击方法切换到GeoActivityGeoActivity返回TextView中当前位置的坐标,并通过HTTP POST将它们发送到远程服务器。 我有一个Handler.class执行后会在50秒后发送邮件。这样的事情如下。我遇到的问题是,当我单击后退按钮并切换到MainActivity时,我仍然可以在LogCat中看到从服务器接收数据仍在发送的回声。我怎么能阻止它?

GeoActivity.class

public class GeoActivity extends Activity {
Location location;
private Handler mHandler = new Handler();

protected void onCreate(Bundle savedInstanceState) {
....

if(location != null){
    mHandler.postDelayed(updateTask,0);
}
...
}
...
public Runnable updateTask = new Runnable(){
public void run(){
    mlocListener.onLocationChanged(location);
    //send coordinates with a delay of 50s
    new PostHttp(getUDID(),latitude,longitude).execute();
    mHandler.postDelayed(updateTask, 50000);
}

1 个答案:

答案 0 :(得分:1)

尝试按活动的生命周期行事。

例如:

@Override
protected void onStop() {
    super.onStop();  // Always call the superclass method first

    // Save the note's current draft, because the activity is stopping
    // and we want to be sure the current note progress isn't lost.
    ContentValues values = new ContentValues();
    values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText());
    values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle());

    getContentResolver().update(
            mUri,    // The URI for the note to update.
            values,  // The map of column names and new values to apply to them.
            null,    // No SELECT criteria are used.
            null     // No WHERE columns are used.
            );
}

这不破坏活动,它将驻留在内存中。但是,您可以随时恢复。

来源:

Stopping and Restarting Android Activities