Android Service…application crashes when making a

2019-08-24 03:44发布

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?

3条回答
不美不萌又怎样
2楼-- · 2019-08-24 04:18

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();
            }
         });
    }
查看更多
来,给爷笑一个
3楼-- · 2019-08-24 04:22

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?

查看更多
我只想做你的唯一
4楼-- · 2019-08-24 04:33

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();
}
查看更多
登录 后发表回答