转载请注明出处:service服务_Mr_Leixiansheng的博客-优快云博客
通过bindService()得到的Service是和启动源(Activity)绑定在一起的,在Activity退出的时候需要调用unbindService()进行解绑定(停止)。
调用bindService()时会调用到目标Service的onBind()函数,通过IBinder接口实例,返回一个ServiceConnection对象给启动源。然后启动源可以通过ServiceConnection对象得到启动的Service对象 1. 使用方法: (1)重写onBind()方法 public IBinder onBind(Intent intent) { return new MyBinder(); } (2)MyBinder是继承自Binder类的,而Binder类实际上实现了IBinder接口 public class MyBinder extends Binder{ public MyBindService getService(){ return MyBindService.this; //返回这个Service的实例 } } (3)在启动源的Activity中创建一个ServiceConnection实例 ServiceConnection conn = new ServiceConnection() { //当启动源跟service的连接意外丢失的时候会调用 //比如service崩溃了,或被强行杀死了 public void onServiceDisconnected(ComponentName name) { } //当启动源跟service成功连接之后会调用这个方法 public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub MyBindService myService = ((MyBinder)service).getService(); } }; (4)bindService()中指定ServiceConnection conn参数
bindService(intent2, conn, Service.BIND_AUTO_CREATE);
demo:
package com.example.administrator.servicetest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button startService;
private Button stopService;
private Button bind;
private Button unbind;
private Button startIntent;
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
downloadBinder = (MyService.DownloadBinder) iBinder;
downloadBinder.startDOwnload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) findViewById(R.id.start);
stopService = (Button) findViewById(R.id.stop);
bind = (Button) findViewById(R.id.bind);
unbind = (Button) findViewById(R.id.unbind);
startIntent = (Button) findViewById(R.id.start_intent);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
bind.setOnClickListener(this);
unbind.setOnClickListener(this);
startIntent.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.start:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
break;
case R.id.stop:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
break;
case R.id.bind:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
break;
case R.id.unbind:
unbindService(connection);
break;
case R.id.start_intent:
Log.i("MainActivity", "Thread is " + Thread.currentThread().getId());
Intent intent = new Intent(MainActivity.this, MyIntentService.class);
startService(intent);
break;
default:
break;
}
}
}
package com.example.administrator.servicetest;
import android.app.DownloadManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by Administrator on 2016/11/24.
*/
public class MyService extends Service {
private DownloadBinder mBinder = new DownloadBinder();
class DownloadBinder extends Binder {
public void startDOwnload() {
Log.i("MyService", "startDownload");
}
public int getProgress() {
Log.i("MyService", "getProgress");
return 0;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
Notification.Builder builder = new Notification.Builder(MyService.this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("这是标题");
builder.setContentText("这是文本");
builder.setWhen(System.currentTimeMillis());
Intent notificationIntent = new Intent(MyService.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivities(MyService.this, 0, new Intent[] {notificationIntent}, 0);
Notification notification = builder.build();
startForeground(1, notification);
Log.i("MyService","onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("MyService","onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("MyService","onDestroys");
}
}
package com.example.administrator.servicetest;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
/**
* Created by Administrator on 2016/11/28.
*/
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
//接收从活动传过来的数据
Log.i("MyIntentService", "Thread is " + Thread.currentThread().getId());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("MyIntentService", "onDestroy");
}
}
//接收从活动传过来的数据
Log.i("MyIntentService", "Thread is " + Thread.currentThread().getId());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("MyIntentService", "onDestroy");
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.administrator.servicetest">
<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"></service>
<service android:name=".MyIntentService"></service>
</application>
</manifest>
使用Ibinder可获取服务对象,在对service做相关操作
package com.leixiansheng.keepservice; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; /** * Created by Leixiansheng on 2017/12/8. */ public class MyService extends Service { private static final String TAG = "MyService"; private MyBinder binder = new MyBinder(); private boolean isExit = false; public class MyBinder extends Binder { public MyService getService() { Log.i(TAG, "--------getService-------"); return MyService.this; //返回服务对象 } } @Nullable @Override public IBinder onBind(Intent intent) { Log.i(TAG, "--------onBind-------"); return binder; } @Override public void onCreate() { super.onCreate(); Log.i(TAG, "--------onCreate-------"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i(TAG, "--------onStartCommand-------"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.i(TAG, "--------onDestroy-------"); } }
startService生命周期
12-02 15:23:31.032 28293-28293/com.leixiansheng.test I/TAG: onCreate 12-02 15:23:31.032 28293-28293/com.leixiansheng.test I/TAG: onStartCommand 12-02 15:23:32.732 28293-28293/com.leixiansheng.test I/TAG: onStartCommand 12-02 15:23:35.442 28293-28293/com.leixiansheng.test I/TAG: onDestroy
bindService生命周期
12-02 15:26:41.012 31716-31716/com.leixiansheng.test I/TAG: onCreate 12-02 15:26:41.012 31716-31716/com.leixiansheng.test I/TAG: onBind 12-02 15:26:41.032 31716-31716/com.leixiansheng.test I/TAG: method in binder 12-02 15:26:41.032 31716-31716/com.leixiansheng.test I/TAG: onServiceConnected 12-02 15:26:52.772 31716-31716/com.leixiansheng.test I/TAG: onDestroy
startService、bindService生命周期
12-02 15:27:52.512 774-774/com.leixiansheng.test I/TAG: onCreate 12-02 15:27:52.512 774-774/com.leixiansheng.test I/TAG: onStartCommand 12-02 15:27:52.512 774-774/com.leixiansheng.test I/TAG: onBind 12-02 15:27:52.522 774-774/com.leixiansheng.test I/TAG: method in binder 12-02 15:27:52.522 774-774/com.leixiansheng.test I/TAG: onServiceConnected 12-02 15:27:57.022 774-774/com.leixiansheng.test I/TAG: onDestroy
bindService补充:通过onBind()返回到的数据可以通过onServiceConnected获取到binder,通过调用binder的方法可以实现Activity 和Service之间的通信功能。
Service虽然是服务,但是如果做还是操作会产生ANR问题,所以使用IntentService来解决这个问题。 客户端通过startService(Intent)来启动IntentService; 我们并不需要手动地区控制IntentService,当任务执行完后,IntentService会自动停止; 可以启动IntentService多次,每个耗时操作会以工作队列的方式在IntentService的 onHandleIntent回调方法中执行,并且每次只会执行一个工作线程,执行完一,再到二这样!
IntentService生命周期:(执行完后自动销毁)
12-02 16:25:02.692 13801-13801/com.leixiansheng.test I/TAG: onCreate: 12-02 16:25:02.692 13801-13801/com.leixiansheng.test I/TAG: onStartCommand: 12-02 16:25:02.692 13801-13962/com.leixiansheng.test I/TAG: onHandleIntent:intent.getStringExtra() 12-02 16:25:02.702 13801-13801/com.leixiansheng.test I/TAG: onDestroy: