代码创建LinearLayout,Services监听线程

1.主Activity:

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值