长延迟AsyncTask和重启任务

时间:2016-07-16 12:13:41

标签: android android-asynctask

我想实现这个功能: 当用户单击按钮启动任务并在5分钟后将一个文件发送到dropbox,但如果用户单击该按钮上的另一个时间,则先前任务中止并启动新任务(5分钟)。

我编写代码将文件上传到Dropbox,但是从未使用如此长时间(5分钟)的任务编写代码。 怎么办?

- 编辑 -

感谢@ xdevs23,我已经实现了最终代码

public void onSendOrder() {

        try {
            mHandler.removeCallbacks(postRunnable); // stop current wait
        } catch(Exception ex) {
            // Just if the above fails (might be first time)
            ex.printStackTrace();
        }
        int minutes = 5;
        mHandler.postDelayed(postRunnable, minutes * 20 * 1000 /* 5 minutes in milliseconds */);
...
...
...

private Runnable postRunnable = new Runnable() {
        @Override
        public void run() {
            Thread myThread = new Thread(myRunnable);
            myThread.start();
        }
    };


    private Runnable myRunnable = new Runnable() {
            @Override
            public void run() {
                // your code
                int cloud = GetPreferenceCloud();
                if(cloud > 0){
                    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
                    final File bckDatabase = BackupDatabase();

                    if (networkInfo != null && networkInfo.isConnected() && bckDatabase != null) {

                    runOnUiThread(new Runnable() {
                        public void run() {
                            // call your asynctask here
                            new UploadOnCloud(MainActivity.this,
                                    PreferenceConstants.DB_DATABASE_STORE_CLOUD,
                                    PreferenceConstants.FILE_DIR_CLOUD,
                                    bckDatabase,
                                    mUListener,
                                    cloud).execute();
                        }
                    });

                } else {
                        Toast.makeText(getContext(),getContext().getResources().getString(R.string.send_msg13), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        };

*编辑。 V2 *

为了实现状态栏上的倒计时我实现了这个:

修改onSend功能:

public void onSendOrder() {

        try {
            mHandler.removeCallbacks(postRunnable); // stop current wait
        } catch(Exception ex) {
            // Just if the above fails (might be first time)
            ex.printStackTrace();
        }
        minute = 3600;
        //mHandler.postDelayed(postRunnable, minutes * 20 * 1000 /* 5 minutes in milliseconds */);
        mHandler.postDelayed(postRunnable, 1000 /* 1 seconds */);

.... ....

在文件menu.xml中

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/break_timer"
          android:title="00:00"
          app:showAsAction="always"
          app:actionViewClass="android.widget.TextView" />
    <item
        android:id="@+id/action_refresh"
        android:title="@string/action_refresh"
        app:showAsAction="ifRoom"
        android:icon="@drawable/ic_action_autorenew"/>
</menu>

修改onCreateOptionsMenu

 public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem timerItem = menu.findItem(R.id.break_timer);
        timerText = (TextView) MenuItemCompat.getActionView(timerItem);
        timerText.setPadding(10, 0, 10, 0); //Or something like that...

        return super.onCreateOptionsMenu(menu);
    }


private int minute;
    private Runnable postRunnable = new Runnable() {
        @Override
        public void run() {
            if(minute >= 0){
                minute--;
                mHandler.postDelayed(postRunnable, 1000 /* 1 seconds */);
                timerText.setText(secondsToString(minute));
            }else {
                Thread myThread = new Thread(myRunnable);
                myThread.start();
            }
        }
    };

1 个答案:

答案 0 :(得分:2)

您可以使用AsyncTaskThread来代替使用Runnable

创建一个Runnable,其中您要在后台运行的代码位于:

Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        // your code
    }
}

创建Thread

private Thread myThread;

确保在主线程上创建了处理程序。 要获得最佳效果,请将其添加到onCreate()方法中:

private Handler mHandler;

@Override
public void onCreate() {
    // ...
    mHandler = new Handler();
    // ...
}

您需要导入android.os.Handler

声明上传代码所在的runnable:

private Runnable postRunnable = new Runnable() {
    @Override
    public void run() {
        Thread myThread = new Thread(myRunnable);
        myThread.start();
    }
}

现在,当用户点击按钮时,请执行以下操作:

try {
    mHandler.removeCallbacks(postRunnable); // stop current wait
} catch(Exception ex) {
    // Just if the above fails (might be first time)
}
int minutes = 5;
mHandler.postDelayed(postRunnable, minutes * 60 * 1000 /* 5 minutes in milliseconds */);

就是这样。

<强>解释

当用户点击按钮时,它将等待(不阻止UI)5秒钟,然后它将运行postRunnable内的代码,这将在后台启动一个新线程,该线程将运行您myRunnable

中的代码

修改以更新通知

private Handler mHandler;
private int minutes = 5;
private Runnable updateRunnable = new Runnable() {
    @Override
    public void run() {
        if(minutes > 0) {
            String notifContent = "" + minutes + " remaining.";
            // Create your notification (there are several guides which show you how to do this), use notifContent as title or text or whatsoever
            minutes--;
            mHandler.postDelayed(updateRunnable, 60 * 1000);
        } else {
            // Remove your notification
        }
    }
};

开始倒计时:

mHandler.post(updateRunnable);