2种方式启动服务
package com.bw.ffuwu;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private Intent intent;
private MyService.MyBinder binder;
private ServiceConnection connection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//启动服务
public void qidong(View view) {
intent = new Intent(this,MyService.class);
startService(intent);
}
//关闭服务
public void xiaohui(View view) {
stopService(intent);
}
//绑定方式启动服务
public void bangqidong(View view) {
Intent intent1 = new Intent(this,MyService.class);
connection= new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
binder= (MyService.MyBinder) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.i("qqq", "onServiceDisconnected: "+"异常时调用");
}
};
bindService(intent,connection,BIND_AUTO_CREATE);
}
//解绑服务
public void jiebang(View view) {
unbindService(connection);
}
//调用服务的方法
public void diao(View view) {
binder.callshow();
}
}
package com.bw.ffuwu;
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();
Log.i("qqq", "onCreate: ");
}
//运行
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("qqq", "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
//销毁
@Override
public void onDestroy() {
super.onDestroy();
Log.i("qqq", "onDestroy: ");
}
class MyBinder extends Binder{
public void callshow(){
show();
}
}
//
@Override
public IBinder onBind(Intent intent) {
Log.i("qqq", "onBind: ");
return new MyBinder();
}
public void show(){
Log.i("qqq", "show: ");
}
}