2011-04-13 95 views
0

當應用程序崩潰這是我的服務類:Android的服務......讓敬酒

public class MySrv extends Service { 

@Override 
public void onCreate() { 
    // TODO Auto-generated method stub 
    super.onCreate(); 
    final Context c = getApplicationContext(); 
    Timer t = new Timer("mytimer"); 
    TimerTask task = new TimerTask() { 
     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      Toast.makeText(c, "Not a beautyfull day today...", Toast.LENGTH_SHORT).show(); 
     } 
    }; 
    t.schedule(task, 5000, 6000); 
} 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 
    return null; 
    } 

}

在Toast.makeText()的應用程序崩潰...所以我在做什麼錯?

+0

請發表您的logcat輸出(logcat的視圖Eclipse或在shell'ADB logcat') – 2011-04-13 15:38:03

+0

你肯定崩潰在Toast.makeText()?你嘗試調試嗎? – yogsma 2011-04-13 15:38:21

回答

3

TimerTaskrun()方法不會在UI線程中執行,因此您不能執行UI相關的操作,例如創建Toast

調查使用HandlerrunOnUiThread()來代替。

例子:

final Handler handler = new Handler(); 
    TimerTask task = new TimerTask() { 
    @Override 
    public void run() { 
     handler.post (new Runnable(){ 
      @Override 
      public void run() { 
       Toast.makeText(c, "Not a beautyfull day today...", Toast.LENGTH_SHORT).show(); 
      } 
     }); 
    } 
+0

也看這個鏈接:http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html – Olegas 2011-04-13 15:43:28

1

你不能在另一個線程敬酒,你可以使用一個處理器來做到這一點,或使用runOnUiThread。

public class YourActivity extends Activity { 
private Handler toastTeller; 
public void onCreate(Bundle savedInstance) { 
    super.onCreate(savedInstance); 
     toastTeller = new Handler() { 
      public void handleMessage(Message msg) { 
      if (msg.what == 2) 
       Toast.makeText(LibraryActivity.this, msg.obj.toString(), 
        Toast.LENGTH_LONG).show(); 
      super.handleMessage(msg); 
      } 
     }; 
    new Thread(new Runnable(){ 
     public void run(){ 
     Message msg = new Message(); 
     msg.what = 2; 
     msg.obj = "Your item was downloaded."; 
     toastTeller.sendMessage(msg); 
     } 
}).start(); 
}