#AsyncTaskの処理をタイムアウトさせる こんな感じ
new ExAsyncTask().setTimeOut(1000).execute();
public class ExAsyncTask extends AsyncTask<Void, Void, Void>{
/** TAG.*/
private static final String TAG = ExAsyncTask.class.getSimpleName();
/** Time-Out(milliseconds).*/
private long mTimeOut = -1;
/**
* Invoked when the running task has timed out.
*/
private Runnable mTimeOutTask = new Runnable() {
@Override
public void run() {
try {
get(mTimeOut, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.e(TAG, null, e);
} catch (ExecutionException e) {
Log.e(TAG, null, e);
} catch (TimeoutException e) {
Log.i(TAG, "Running task has timed out!!", e);
if (isCancelled() && getStatus() == Status.RUNNING) {
ExAsyncTask.this.cancel(true);
}
}
}
};
@Override
protected Void doInBackground(Void... params) {
if (mTimeOut > 0) {
new Thread(mTimeOutTask).start();
}
//do someting
return null;
}
/**
* Set the time-out.
* @param timeOut milliseconds
* @return this
*/
public ExAsyncTask setTimeOut(long timeOut) {
mTimeOut = timeOut;
return this;
}
}