最終更新:
bokkuri_orz 2014年12月29日(月) 02:39:02履歴
public class MainActivity extends ActionBarActivity
{
Handler m_handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState)
{
// ボタンを押した時に、時間のかかる処理をしてからTextViewを更新する
Button btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
// 時間のかかる処理を非同期で行う
Thread thread = new Thread(new Runnable(){
public void run()
{
// 時間のかかる処理
// MainActivityのUI操作
// Handlerを利用する
m_handler.post(new Runnable(){
m_textView.setText(/*何かの文字列*/);
});
}
});
thread.start();
}
});
}
}
AndroidのThread, Handler, Looperの仕組みが解説されていて、Handlerを使う理由が理解できます。
http://www.adamrocker.com/blog/261/what-is-the-han...
アクティビティが終了しても、HandlerがActivityへの参照を持っているため、GCで回収されない。
その問題の解決方法。
public TestActivity extends Activity
{
private static TestHandler extends Handler
{
private final WeakReference<TestActivity> m_ref;
TestHandler(TestActivity act)
{
m_ref = new WeakReference<TestActivity>(act);
}
@Override
public void handleMessage(Message msg)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
TestActivity act = m_ref.get();
if(act != null) act.func();
}
}
private TestHandler m_handler = new TestHandler(this);
private void func()
{
// ActivityのUI更新処理
}
}
Handlerのリーク警告を解決するには
http://outcesticide.hatenablog.com/entry/handler_l...
http://glayash.blogspot.jp/2012/08/handleleak.html
This Handler class should be static or leaks might occur: IncomingHandler
http://stackoverflow.com/questions/11407943/this-h...


最新コメント