use*_*158 3 java service multithreading android class
我创建了一个服务类,现在我试图在这个类中运行一个新线程.服务在我的服务中开始MainActivity,这很有效.该部分Toast.Message中的onCreate()第一个显示,但我的线程runa()中的消息没有出现.认为它应该与新的一起工作Runnable().
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
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人能帮助我会很好:)
在Thread对正在创建,将不会被执行MainThread,因此你不能表现出Toast如此.要从Toast背景中显示a ,Thread您必须使用a Handler,并使用它Handler来显示Toast.
private MyService extends Service {
Handler mHandler=new Handler();
//...
public void runa() throws Exception{
mHandler.post(new Runnable(){
public void run(){
Toast.makeText(MyService.this, "test", Toast.LENGTH_LONG).show()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将是您确切问题的解决方案,虽然我不认为它是一个好的"架构"或练习,因为我不知道您想要实现什么.
| 归档时间: |
|
| 查看次数: |
16786 次 |
| 最近记录: |