Service是Android四大组件之一,使用时可以在后台操作,他并不与用户产生UI交互。其他组件也可以启动,用户切换其他的应用,启动后的Service仍在后台。一个组件可以与Service绑定并与之交互,甚至可以跨进程通信。并且可以在后台执行网络请求,播放音乐,执行文件等操作。
代码内有详细注解
主函数
package com.example.servicedemo;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
//IBinder
//ServicerConnection:用于绑定客户端和Service
//进度监控
private ServiceConnection conn = new ServiceConnection() {
//当客户端正常连接着服务时,执行服务的绑定操作会被调用
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.e("TAG","慕课");
MyService.MyBinder mb = (MyService.MyBinder) iBinder;
int step = mb.getProcess();
Log.e("TAG","当前进度是:" + step);
}
//当客户端和服务的连接丢失了
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void operate(View v){
switch (v.getId()){
case R.id.start:
//启动服务:创建-->启动-->销毁
//如果服务已经创建了,后续重复启动,操作的都是同一个服务,不会再重新创建了,除非你先销毁它
Intent it1 = new Intent(this,MyService.class);
startService(it1);
break;
case R.id.stop:
Intent it2 = new Intent(this,MyService.class);
stopService(it2);
break;
case R.id.bind:
//绑定服务:最大的 作用是用来实现对Service执行的任务进行进度监控
//如果服务不存在: onCreate-->onBind-->onUnbind-->onDestory
// (此时服务没有再后台运行,并且它会随着Activity的摧毁而解绑并销毁)
//服务已经存在:那么bindService方法只能使onBind方法被调用,而unbindService方法只能使onUnbind被调用
Intent it3 = new Intent(this,MyService.class);
bindService(it3, conn,BIND_AUTO_CREATE);
break;
case R.id.unbind:
//解绑服务
unbindService(conn);
break;
}
}
}
Service代码
package com.example.servicedemo;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;
import java.io.FileDescriptor;
public class MyService extends Service {
public MyService() {
}
private int i;
//创建[34
@Override
public void onCreate() {
super.onCreate();
Log.e("TAG","服务创建了");
//开启一个线程(从1数到100),用于模拟耗时的任务
new Thread(){
@Override
public void run() {
super.run();
try {
for (i = 1; i <= 100; i++) {
sleep(1000);
}
}catch (Exception e){
e.printStackTrace();
}
}
}.start();
}
//启动
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("TAG","服务启动了");
return super.onStartCommand(intent, flags, startId);
}
//绑定
//IBinder:在android中用于远程操作对象的一个基本接口
@Override
public IBinder onBind(Intent intent) {
Log.e("TAG","服务绑定了");
return new MyBinder();
}
//对于onBind方法而言,要求返回IBinder对象
//实际上,我们会自己定义一个内部类,集成Binder类
class MyBinder extends Binder{
//定义自己需要的方法(实现进度监控)
public int getProcess(){
return i;
}
}
//解绑
@Override
public boolean onUnbind(Intent intent) {
Log.e("TAG","服务解绑了");
return super.onUnbind(intent);
}
//摧毁
@Override
public void onDestroy() {
super.onDestroy();
Log.e("TAG","服务销毁了");
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.servicedemo.MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="启动服务"
android:onClick="operate" />
<Button
android:id="@+id/stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="停止服务"
android:onClick="operate" />
<Button
android:id="@+id/bind"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="绑定服务"
android:onClick="operate" />
<Button
android:id="@+id/unbind"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="解绑服务"
android:onClick="operate"/>
</LinearLayout>
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.servicedemo">
<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"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.imooc.myservice"/>
</intent-filter>
</service>
</application>
</manifest>