开发者

Android Service...application crashes when making a Toast

This is my Service class:

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;
    }

}

The application crashes开发者_开发问答 at Toast.makeText()... So what am I doing wrong?


The TimerTask's run() method doesn't execute in the UI thread, so you can't do UI-related things like creating a Toast.

Investigate using a Handler or runOnUiThread() instead.

Example:

    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();
            }
         });
    }


The problem here is that you are trying to update the UI in the timers thread, you should use a Handler for this.

Read How to display toast inside timer?


You cannot make a Toast in another Thread, you can use a Handler to do it or use the 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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜