(这里只有bind启动的方法)
1.先创建一个服务
2.Service里的代码
package com.example.zuoye;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
return new MyServer();
}
class MyServer extends Binder{
public void aaa(){
Toast.makeText(MyService.this, "hhh", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
}
3.在activity中启动服务
package com.example.zuoye;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private ServiceConnection serviceConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.MyServer service1 = (MyService.MyServer) service;
service1.aaa();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, MyService.class);
bindService(intent,serviceConnection,BIND_AUTO_CREATE);
}
}