3

我创建了一个服务类,现在我正在尝试在这个类中运行一个新线程。我的服务开始了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

    }
}

如果有人可以帮助我会很好:)

4

3 回答 3

5

您正在创建的Thread将不会在 上执行MainThread,因此您无法从中显示 a ToastToast要从背景显示 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()
            }
        }
    }    
}

这将是您确切问题的解决方案,尽管我不认为它是一个好的“架构”或实践,因为我不知道您想要实现什么。

于 2013-05-09T11:03:43.827 回答
0

您不能显示来自非 UI 线程的 Toast。您的服务在主线程上运行,但您runa()在后台线程中运行您的方法。您必须使用处理程序并要求它在 UI 线程上显示 toast。请参阅此答案以了解这是如何完成的。

于 2013-05-09T10:51:07.713 回答
0

从线程更新 UI 的最佳方法是使用处理程序或 UIThread

试试这个代码:不要忘记先把服务放到Manifest文件中。

class CapturingSerivce extends Service {
 Handler mHandler=new Handler();

@Override
public IBinder onBind(Intent intent) {
    return null;
}

 public void runa() throws Exception{
        mHandler.post(new Runnable(){
            public void run(){

            }
        });
    }    


@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    return super.onStartCommand(intent, flags, startId);
  }
}
于 2014-06-11T20:47:52.427 回答