<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
tools:context="org.frxm.bindservice.MainActivity">
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="绑定服务"
android:onClick="click"/>
<Button
android:id="@+id/btnEnd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="解绑服务"
android:onClick="click"/>
</LinearLayout>
package org.frxm.bindservice;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
public MyService() {
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
class MyBinder extends Binder{
public String download(String msg){
Log.i("tag",msg);
return "下载完成";
}
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
package org.frxm.bindservice;
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.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view) {
Intent intent=new Intent(this,MyService.class);
switch (view.getId()){
case R.id.btnStart:
//绑定服务
bindService(intent,connection,BIND_AUTO_CREATE);
break;
case R.id.btnEnd:
unbindService(connection);//解绑服务
break;
}
}
ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.MyBinder binder=(MyService.MyBinder)service;
String download = binder.download("开始下载");
Log.i("tag",download);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onDestroy() {
super.onDestroy();
}
}
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>