package com.example.yabushan.hello3;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyService extends Service {
private boolean SERVICE_STATE=true;
private String data="默认值";
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return new binder();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("startCommand");
return super.onStartCommand(intent, flags, startId);
}
public class binder extends Binder{
public void setData(String data){
MyService.this.data=data;
}
}
@Override
public void onCreate() {
super.onCreate();
new Thread(){
@Override
public void run() {
super.run();
while(SERVICE_STATE){
System.out.println(data);
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
package com.example.yabushan.hello3;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity implements View.OnClickListener, ServiceConnection {
private Intent intent;
private MyService.binder binder;
private TextView editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
editText= (TextView) findViewById(R.id.backText);
intent=new Intent(MainActivity.this,MyService.class);
findViewById(R.id.startService).setOnClickListener(this);
findViewById(R.id.stopService).setOnClickListener(this);
findViewById(R.id.bindService).setOnClickListener(this);
findViewById(R.id.unbindService).setOnClickListener(this);
findViewById(R.id.syncData).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.startService:
startService(intent);break;
case R.id.stopService:
stopService(intent);break;
case R.id.bindService:
bindService(intent, this, Context.BIND_AUTO_CREATE);break;
case R.id.unbindService:
unbindService(this);break;
case R.id.syncData://数据同步
if(binder!=null)
binder.setData(editText.getText().toString());
break;
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("服务绑定成功");
binder= (MyService.binder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("服务解绑成功");
}
}
binder