今天写博客时间有点晚了,主要是因为下午在写Service使用Demo的时候遇到了一些问题,那么接下来就开始分析Service的使用和生命周期吧~
实际使用
我写了一个简单的demo,包含了Service的两种启动方式,我先贴出源码和运行截图.文件总共有ServiceActivity.java,MyService.java,activity_service.xml,style.xml四个文件,在日志的打印中我没有使用复杂的接口,直接使用了静态方法的方式打印了数据,这种方式仅仅只能在单个Activity的demo中使用,切记不要在实际开发中这样操作,不然你会非常容易地遇到空指针~
ServiceActivity.java
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import com.txVideo.demo.service.MyService;
import java.util.List;
public class ServiceActivity extends AppCompatActivity implements View.OnClickListener {
public static final String TAG = "ServiceActivity";
private Button startBtn;
private Button stopBtn;
private Button bindBtn;
private Button unbindBtn;
private Button clearBtn;
private static ScrollView logScrollView;
private static TextView logTextView;
private static StringBuffer logStringBuffer = new StringBuffer();
private MyService myService = new MyService();
private MyConnection conn = new MyConnection();
private boolean isBinding ;
public static Handler mHandler = new Handler(){
@Override
public void handleMessage(Message message){
log();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
initView();
}
public void initView(){
startBtn = findViewById(R.id.start_service_btn);
stopBtn = findViewById(R.id.stop_service_btn);
bindBtn = findViewById(R.id.bind_service_btn);
unbindBtn = findViewById(R.id.unbind_service_btn);
clearBtn = findViewById(R.id.service_clear_btn);
logScrollView = findViewById(R.id.service_log_scroll);
logTextView = findViewById(R.id.service_log);
startBtn.setOnClickListener(this);
stopBtn.setOnClickListener(this);
bindBtn.setOnClickListener(this);
unbindBtn.setOnClickListener(this);
clearBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.start_service_btn:
//startService方式打开
Intent myServiceIntent1 = new Intent(this,MyService.class);
startService(myServiceIntent1);
break;
case R.id.stop_service_btn:
//stopService方式关闭
if(!isServiceRunning(this,MyService.class.getName())){
sendMessageForLog("服务未运行------");
break;
}
Intent myServiceIntent2 = new Intent(this,MyService.class);
stopService(myServiceIntent2);
break;
case R.id.bind_service_btn:
if( isBinding && isServiceRunning(this,MyService.class.getName())){
sendMessageForLog("服务已经绑定------");
break;
}
Intent bindService = new Intent(this,MyService.class);
//通过绑定的方式开启service
//使用bindService 开启反服务
//参数 1. intent 包含要启动的service
//2. ServiceConnection接口 通过它可以接受服务开启或者停止的消息
//3.开启服务时操作的选项 一般传入BIND_AUTO_CREATE自动创建service
bindService(bindService, conn, BIND_AUTO_CREATE);//绑定存在自动创建
break;
case R.id.unbind_service_btn:
//解绑
if(isServiceRunning(this,MyService.class.getName()) && isBinding){
unbindService(conn);
isBinding = false ;
sendMessageForLog("服务已解绑------");
break;
}
if(!isServiceRunning(this,MyService.class.getName())){
sendMessageForLog("服务未运行------");
break;
}
if(!isBinding){
sendMessageForLog("服务运行但未绑定------");
break;
}
break;
case R.id.service_clear_btn:
sendMessageForLog("");
break;
}
}
public static void log(){
logTextView.setText(logStringBuffer.toString());
logScrollView.post(new Runnable() {
@Override
public void run() {
logScrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
/**
* 发送消息,在主线程里更新UI
*/
public static void sendMessageForLog(String s){
if("".equals(s)){
logStringBuffer.delete(0,logStringBuffer.length());
}else {
logStringBuffer.append(s+"\n");
}
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("data",logStringBuffer.toString());
mHandler.sendMessage(message);
}
private class MyConnection implements ServiceConnection {
@Override//当服务与Activity 连接时建立
public void onServiceConnected(ComponentName name, IBinder service) {
//只有当service onbind方法返回值不为null 调用
sendMessageForLog("服务已经绑定------onServiceConnected()");
isBinding = service.isBinderAlive();
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e("TAG", "onServiceDisconnected");
sendMessageForLog("服务已经断开绑定------onServiceConnected()");
}
}
/**
* 校验服务是否还存在
*/
public static boolean isServiceRunning(Context context, String serviceName){
// 校验服务是否还存在
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(100);
for (ActivityManager.RunningServiceInfo info : services) {
// 得到所有正在运行的服务的名称
String name = info.service.getClassName();
if (serviceName.equals(name)) {
return true;
}
}
return false;
}
}
MyService.java
public class MyService extends Service {
public static final String TAG = "MyService";
private LocalBinder mBinder = new LocalBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
ServiceActivity.sendMessageForLog("服务已经绑定------onBind()");
return mBinder;
}
@Nullable
@Override
public void unbindService(ServiceConnection serviceConnection){
ServiceActivity.sendMessageForLog("服务已解除绑定------unbindService()");
super.unbindService(serviceConnection);
}
@Override
public void onCreate() {
ServiceActivity.sendMessageForLog("服务已经创建------onCreate()");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
ServiceActivity.sendMessageForLog("服务已经开启------onStartCommand()");
ServiceActivity.sendMessageForLog("服务已经开启------flags:"+flags);
ServiceActivity.sendMessageForLog("服务已经开启------startId:"+startId);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
ServiceActivity.sendMessageForLog("服务已经关闭------onDestroy()");
super.onDestroy();
}
public class LocalBinder extends Binder{
public MyService getservices(){
return MyService.this;
}
}
布局文件activity_service.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".BroadcastActivity">
<Button
android:id="@+id/start_service_btn"
style="@style/MyStyle"
android:layout_height="wrap_content"
android:text="startService"
android:textAllCaps="false"/>
<Button
android:id="@+id/stop_service_btn"
style="@style/MyStyle"
android:layout_height="wrap_content"
android:text="stopService"
android:textAllCaps="false"/>
<Button
android:id="@+id/bind_service_btn"
style="@style/MyStyle"
android:layout_height="wrap_content"
android:text="bindService"
android:textAllCaps="false"/>
<Button
android:id="@+id/unbind_service_btn"
style="@style/MyStyle"
android:layout_height="wrap_content"
android:text="unbindService"
android:textAllCaps="false"/>
<ScrollView
android:id="@+id/service_log_scroll"
style="@style/MyStyle"
android:layout_height="0dp"
android:layout_weight="1">
<TextView
android:id="@+id/service_log"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</ScrollView>
<Button
android:id="@+id/service_clear_btn"
style="@style/MyStyle"
android:layout_marginBottom="10dp"
android:layout_height="wrap_content"
android:text="清空日志"/>
</LinearLayout>
style.xml文件
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:windowNoTitle">true</item>
</style>
<style name="MyStyle">
<item name="android:layout_marginLeft">10dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:layout_marginRight">10dp</item>
<item name="android:layout_width">match_parent</item>
</style>
</resources>
绑定情况的运行截图为:
Screenshot_2020-02-28-17-31-08-35.png
这个demo包含了两种方式以及组合使用的情况,有兴趣的小伙伴可以copy使用查看生命周期的变化,使用的过程看一下demo程序大家应该就有所了解了,先简单梳理一下正常使用状态下的Service生命周期:
- startService方式启动及关闭
onCreate() - onStartCommand() - onDestroy() - 多次startService打开后关闭
onCreate() - onStartCommand() - onStartCommand() - onDestroy() - bindService方式
onCreate() - onBind() - unBind() - onDestroy() - 组合使用
onCreate() - onStartCommand() - onBind() - unBind() - onDestroy()
总结几个使用的注意点 - Service在运行,不一定被绑定,但被绑定,一定在运行。
- Service多次以startService方式启动时,不会重新调用onCreate()方法,只会走onStartCommand()且对应的startId会依次增加1.
- Service在停止或者解绑时要确定这个Service在运行或者已经被绑定了,否则会出错。
- Service在使用startService启动后,再调用bindService方法,这时如果不先调用unbindService()方法的话,直接调用stopService方法是无法触发Service的onDestroy方法的。
今天的Service使用就总结到这里啦,觉得有帮助记得点个赞~
网友评论