1.主Activity:
2.监听线程的Services:
3.最后是一个简单的接口:
当然这个Services一定要在Manifest.xml中进行申明:
private TextView tx;
private Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(150, 40);
param.topMargin = 5;
tx = new TextView(this);
tx.setTextSize(16);
tx.setTextColor(Color.BLUE);
// tx.setBackgroundResource(R.drawable.x_yellow);
layout.addView(tx, param);
btn = new Button(this);
btn.setText("Exit");
// btn.setBackgroundResource(R.drawable.earth);
btn.setOnClickListener(this);
layout.addView(btn, param);
this.setContentView(layout);
String tna = Thread.currentThread().getName();
Thread.currentThread().setName(tna + "-Ac_and_Se");
MyService.setUpdateListener(new UpdateUIListener());
Intent svc = new Intent(this, MyService.class);
startService(svc);
}
public void onClick(View v) {
this.finish();
}
class UpdateUIListener implements IListener {
public void update(String s) {
System.out.println("__________________"+s);
tx.setText(s);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
{
Intent svc = new Intent(this, MyService.class);
stopService(svc);
}
}
2.监听线程的Services:
public class MyService extends Service {
// 监听器对象的实例
private static IListener plis;
// private static int k = 0;
private Timer timer = new Timer();
private String tna;
public Handler handler = new Handler() {
public void handleMessage(Message msg) {
plis.update(tna);
}
};
@Override
public void onCreate() {
super.onCreate();
tna = Thread.currentThread().getName();
TimerTask task = new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(0);
}
};
timer.schedule(task, 1000, 4000);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public static void setUpdateListener(IListener listener) {
plis = listener;
}
}
3.最后是一个简单的接口:
public interface IListener {
public void update(String s);
}
当然这个Services一定要在Manifest.xml中进行申明:
<service android:name=".MyService"></service>