https://www.bilibili.com/video/BV19F411h7fE?p=49
service的:create、start、destroy
首先要注册
package com.example.wechatpage;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
public class MyService extends Service {
private static final String TAG = MyService.class.getSimpleName();
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: ");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(TAG, "onStart: ");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: "+intent);
return null;
}
@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind: "+intent);
return super.onUnbind(intent);
}
}
Button btn_s = rootView.findViewById(R.id.btn_start_service);
btn_s.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getContext().startService(new Intent(getContext(), MyService.class));
}
});
View btn_stop = rootView.findViewById(R.id.btn_stop_service);
btn_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getContext().stopService(new Intent(getContext(), MyService.class));
}
});
<Button
android:id="@+id/btn_start_service"
android:text="start service"
android:layout_width="wrap_content"
android:layout_height="70dp"
android:layout_gravity="center_horizontal"/>
<Button
android:id="@+id/btn_stop_service"
android:text="start service"
android:layout_width="wrap_content"
android:layout_height="70dp"
android:layout_gravity="center_horizontal"/>
开始service之后,调用create、startCommand、start
进入后台,没有变化
关闭应用之后调用了craete、destroy
可以看到是不同的线程日志,应该是android的垃圾回收机制调用的,而不是应用本身
主动停止服务,调用destroy
service的:bind、unbind
bind、unbind和上面的不同,他们和activity的生命周期挂钩
rootView.findViewById(R.id.btn_bind_service).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getContext().bindService(new Intent(getContext(), MyService.class), connect, Context.BIND_AUTO_CREATE);
}
});
rootView.findViewById(R.id.btn_unbind_service).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getContext().unbindService(connect);
}
});
return rootView;
}
private ServiceConnection connect = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.d(TAG, "onServiceConnected: ");
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.d(TAG, "onServiceDisconnected: ");
}
};