标签:
添加按钮
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="默认信息"
android:id="@+id/edtData" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动服务"
android:id="@+id/btnStartService" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止服务"
android:id="@+id/btnStopService" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="绑定服务"
android:id="@+id/btnBindService" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="解除绑定"
android:id="@+id/btnUnBindService" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="同步数据"
android:id="@+id/btnSyncData" />
添加MainActivity文件的方法
findViewById(R.id.btnStartService).setOnClickListener(this);
findViewById(R.id.btnStopService).setOnClickListener(this);
findViewById(R.id.btnBindService).setOnClickListener(this);
findViewById(R.id.btnUnBindService).setOnClickListener(this);
findViewById(R.id.btnSyncData).setOnClickListener(this);
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnStartService:
intent = new Intent(this,MyService.class);
intent.putExtra("data", edtData);
startService(intent);
break;
case R.id.btnStopService:
stopService(intent);
break;
case R.id.btnBindService:
bindService(intent, this, Context.BIND_AUTO_CREATE);
break;
case R.id.btnSyncData:
edtData=((EditText)findViewById(R.id.edtData)).getText().toString();
binder.setData(edtData);
break;
default:
break;
}
}
myService文件
public class Binder extends android.os.Binder{
public void setData(String data){
MyService.this.data=data;
}
}
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
running = true;
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
while (running) {
System.out.println("服务正在运行:"+data);
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
System.out.println("service onCreate");
}
mainActivity文件
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
if (binder == null){
binder = (Binder) service;
}
}
标签:
原文地址:http://www.cnblogs.com/cityking/p/a018.html