我創建了一個服務類,現在我試圖在此類中運行新線程。服務在我的MainActivity
開始,這很好。 onCreate()
部分中的第一個Toast.Message
顯示,但我的線程runa()
中的消息沒有出現。認爲它應該與新的Runnable()
一起工作。Android在服務類中創建新線程
public class My Service extends Service {
private static final String TAG = "MyService";
Thread readthread;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show(); //is shown
readthread = new Thread(new Runnable() { public void run() { try {
runa();
} catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
} } });
readthread.start();
Log.d(TAG, "onCreate");
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid) {
//Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
//Log.d(TAG, "onStart");
}
public void runa() throws Exception{
Toast.makeText(this, "test", Toast.LENGTH_LONG).show(); //doesn't show up
}
}
將是很好,如果有人可以幫助我:)
你有什麼異常嗎?我猜''線程'在背景'線程'上執行,你不能顯示吐司。 – 2013-05-09 10:42:27
@OvidiuLatcu你的評論是對他問題的回答。將它作爲答案移動,請 – Blackbelt 2013-05-09 10:43:42
好的,謝謝,有沒有解決方法? – user2295158 2013-05-09 10:50:56