编写绑定的 Service服务
MainActivity
package annoy.service_test;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button1, button2, button3;
BindService.MyBinder binder;
// 定义一个连接ServiceConnection对象
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
System.out.println("--Service Conneciton");
// 获取Service的onBinder方法所返回的MyBinder对象
binder = (BindService.MyBinder) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
System.out.println("--Service Disconnected--");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取界面中的3个按钮
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
// 创建启动Service的Intent
final Intent intent = new Intent(this, BindService.class);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 绑定指定Service
bindService(intent, conn, Service.BIND_AUTO_CREATE);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 解除绑定
unbindService(conn);
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 获取并显示Service的Count值
Toast.makeText(MainActivity.this, "Service的count值为:" + binder.getCount(),
Toast.LENGTH_SHORT).show();
}
});
}
}
Service编写
BindService
package annoy.service_test;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class BindService extends Service
{
private int count = 0;
private boolean quite = false;
// 定义onBinder方法返回的对象
private MyBinder binder = new MyBinder();
// 继承Binder来实现IBunder
public class MyBinder extends Binder
{
public int getCount()
{
return count;
}
}
public BindService() {
}
@Override
public IBinder onBind(Intent intent) {
// throw new UnsupportedOperationException("Not yet implemented");
System.out.println("Service is Binded");
return binder;
}
@Override
public void onCreate()
{
super.onCreate();
System.out.println("Service is Create");
// 启动一条线程
new Thread()
{
@Override
public void run()
{
while (!quite) {
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
count++;
}
}
}.start();
}
@Override
public boolean onUnbind(Intent intent) {
System.out.println("Service is Unbind");
return true;
}
@Override
public void onDestroy() {
super.onDestroy();
this.quite = true;
System.out.println("Service is Destroyed");
}
}