Android Services后台服务案例分析总结

服务的基本要点:
1.后台服务
2.无交互界面,不跟随界面的生命周期
3.比不可见界面的优先级要高,服务经常用于播放音视频的场合。
4.默认情况下,服务和主线程在同一个程序下运行。
一般使用异步处理后台的大量资源计算任务。
要使用服务,一般是在service里创建一个新的线程在后台进行处理,然后处理完毕的时候停止服务。
运行在程序进程中的服务,称为本地服务。

自定义服务:
1.服务需要在AndroidManifest.xml中进行声明,并且服务的实现类需要继承自Service类或者他的子类

<service
    android:name="MyService"
    android:icon="@drawable/icon"
    android:label="@string/service_name"
    >
</service>
public class MyService extends Service {
  @Override
  public IBinder onBind(Intent intent) {
    //TODO for communication return IBinder implementation
    return null;
  }
}

具体代码:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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=".LocalWordService"
            android:label= "Word service"/>
    </application>

2.启动服务
服务,消息接收器,活动页面这三类组件都可以通过执行startService(intent)方法来启动服务。

// use this to start and trigger a service
Intent i= new Intent(context, MyService.class);
// potentially add data to the intent
i.putExtra("KEY1", "Value to be used by the service");
context.startService(i);

3.执行服务
执行startService之后,服务实际上还没有运行的,这时候服务对象被创建了,onCreat()方法被调用。
服务启动的时候,onStartCommand(intent)被调用,此方法因为是在主界面线程中调用,所以无需做同步处理。
无论你调用startService多少次,服务也只是启动一次。

4.结束服务
结束服务使用stopService(),服务本身也可以调用stopSelf()来结束自己。

5.IntentServices,一次性服务
执行一次性任务的时候可以用一次性服务,例如下载任务,任务执行完后,它会自动结束自己。

6.和服务进行通信
活动界面和服务的通信有如下方式:
1.使用Intent数据
2.使用消息接收器
在这里插入图片描述
7.活动界面绑定到本地服务

服务在活动界面的主进程中启动,活动界面可以直接绑定服务。

@Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        LocalWordService.MyBinder b = (LocalWordService.MyBinder) binder;
        s = b.getService();
        Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
    }

具体案例代码如下:
TestLocalService.zip:
testService.zip:

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章