Created
December 22, 2015 08:06
-
-
Save kob-to-wni/084140c5354b5cd55c72 to your computer and use it in GitHub Desktop.
HandlerTask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import android.os.Handler; | |
import android.os.Looper; | |
import java.util.TimerTask; | |
/** | |
* UIスレッドに安全にアクセスできるTimerTaskです | |
* | |
* @author kob-to | |
*/ | |
public abstract class HandlerTask extends TimerTask { | |
/** | |
* デバッグ用タグ | |
*/ | |
private static final String TAG = HandlerTask.class.getSimpleName(); | |
/** | |
* Handler | |
*/ | |
private final Handler mHandler; | |
/** | |
* 現在のスレッドのLooperを使用してHandlerTaskを初期化します | |
*/ | |
public HandlerTask(){ | |
mHandler = new Handler(Looper.getMainLooper()); | |
} | |
/** | |
* 指定されたコンテキストのLooperを使用してHandlerTaskを初期化します | |
* @param context コンテキスト | |
*/ | |
public HandlerTask(Context context){ | |
mHandler = new Handler(context.getMainLooper()); | |
} | |
/** | |
* Looperを指定してHandlerTaskを初期化します | |
* @param looper Looper | |
*/ | |
public HandlerTask(Looper looper){ | |
mHandler = new Handler(looper); | |
} | |
/** | |
* Timerが経過した際に呼ばれます | |
*/ | |
@Override | |
public void run() { | |
mHandler.post(new Runnable() { | |
@Override | |
public void run() { | |
onTimer(); | |
} | |
}); | |
} | |
/** | |
* Timerが経過した際に呼ばれます | |
*/ | |
public abstract void onTimer(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Timerに渡すTimerTaskのメソッドからそのままUIに触ると例外で死んでしまう。かわりにHandlerTaskは内部でHandlerを使うので、安全にUIに触れる。