【发布时间】:2011-06-13 15:44:18
【问题描述】:
我有一个由 MyService 命名的类,它扩展了下面的 Service。一切都将运行到
我删除了Thread的run方法中的Toast.makeText...这一行。
为什么?以及如何从 Thread 类的 run 方法访问 Activity 组件?
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) { return null; }
@Override
public void onCreate() {
Toast.makeText(this, "This msg will be shown", Toast.LENGTH_LONG).show();
Log.d("Bilgi", "This msg will be shown.");
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "This msg will be shown", Toast.LENGTH_LONG).show();
super.onStart(intent, startId);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
Log.d("This msg will ","be shown"); //if I remove next line
Toast.makeText(this, "This msg will NOT be shown", Toast.LENGTH_LONG).show();
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 5000, 8000);
}
【问题讨论】:
标签: android multithreading service android-activity