android服务

Service有两种启动模式:startService和bindService。

1、startService启动的服务,如果在Activity里面没有停止这个服务的话,Activity关闭之后Service还在。

2、bindService启动的服务,Activity关闭了之后Service也关闭了。 bind启动,unbind解除的话服务直接会Destroy。

3、startService和bindService组合使用,先startService启动服务,再bindService绑定服务,Activity与Service进行通信,解除绑定unbindService(此时服务没有destroy),停止服务stopService。

这样就可以实现通信了(同一进程)。

Service的的配置记得加在Application框里面

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.binbin.testbinder">




    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService">
            <intent-filter>
                <action android:name="android.intent.action.MyService" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </service>
    </application>

</manifest>

  

没有绑定服务就解除绑定,会报错。

绑定之后获得了服务的binder,就可以使用自定义的Binder里面的方法了。

原文地址:https://www.cnblogs.com/wzben/p/5719113.html