//用service在后台每一秒随机生成一个数,并用toast来显示 
package edu.neusoft;
//MyService.java 文件
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;public class MyService extends Service {
private Thread thread;
private Runnable backgroundThread = new Runnable() {
double number; public void run() {
try {
while (true) {
Thread.sleep(1000);
number = Math.random();
Toast.makeText(null, String.valueOf(number),
Toast.LENGTH_LONG).show();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}; public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "start service", Toast.LENGTH_LONG).show();
} @Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
thread = new Thread(backgroundThread);
thread.start();
Toast.makeText(this, "create service", Toast.LENGTH_LONG).show();
}
}
//MainActivity.java 文件
package edu.neusoft;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;public class MainActivity extends Activity {
    /** Called when the activity is first created. */
private Button myButton;
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myButton=(Button)findViewById(R.id.Button01);
        myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent();
intent.setAction("Service");
startService(intent);
}
});
    }
}XML文件不写了, 只是一个按钮 

解决方案 »

  1.   

    线程中不能Toast?
    好像线程中要用Hander才能Toast吧?
      

  2.   

    添加一个uihandle ui操作都在ui线程里处理
    private Handler uiHandler = new Handler() {
    public void handleMessage(Message msg) {
    try {
    switch (msg.what) {
    case 0:
    //添加toast语句
    break;
    default:
    super.handleMessage(msg);
    break;
    }
    } finally {
    thread = null;
    }
    }
    在线程里添加一个message,在生成数字后加上这个 就可以通知ui线程去实行toast了
    Message msg = new Message();
    msg.what = 0;
    uiHandler.sendMessage(msg);
      

  3.   

    直接在handler里面postDelayed一个线程实例,指定下时间间隔,然后在这个线程实例里面run完后,继续postDelayed。。
      

  4.   

    UI相关的函数不要在线程中,在主线程内可以用handler处理消息,线程发送消息,你想看效果可以打印log.d看