- 概念
是Context的子类,没有UI界面,是在后台运行的组件。 - 生命周期
(1) 使用context.startService()启动
startService()–>onCreate()–>onStart()(可多次调用)–>Service running
stopService()–>onDestory()–>Service stop
(2) 使用context.bindService()启动
context.bindService()–>onCreate()–>onBind()(只一次,不可多次绑定)–>Service running
onUnbind()–>onDestory()–>Service stop
(《第一行代码》)
/**
* 自定义服务,四大组件都需要注册
*
* @author Administrator
*/
public class MySercice extends Service {
private DownloadBinder mBinder = new DownloadBinder();
// 模拟下载
class DownloadBinder extends Binder {
public void startDownload() {
Log.d("MySerice", "startDownload executed");
}
public void getProgress() {
Log.d("MySerice", "getProgress executed");
return;
}
}
// 建立服务和活动的关系
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// 服务创建时调用
@Override
public void onCreate() {
super.onCreate();
Notification notification = new Notification(R.drawable.ic_launcher, "Notification comes",
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "This is title", "This is content", pendingIntent);
// 变为前台服务,并在系统状态栏显示出来
startForeground(1, notification);
Log.d("MySerice", "onCreate executed");
}
// 每次服务启动的时候调用
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MySerice", "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}
// 服务销毁的时候调用
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyService", "onDestory executed");
}
}
MainActivity
package com.example.servicetest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button startService;
private Button stopService;
private Button bindService;
private Button unbindService;
private Button startIntentService;
private MySercice.DownloadBinder downloadBinder;
private ServiceConnection Connection = new ServiceConnection() {
// 服务解除绑定时调用
@Override
public void onServiceDisconnected(ComponentName name) {
}
// 服务成功绑定时调用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MySercice.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) findViewById(R.id.start_service);
stopService = (Button) findViewById(R.id.stop_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
bindService = (Button) findViewById(R.id.bind_service);
unbindService = (Button) findViewById(R.id.unbind_service);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
startIntentService = (Button) findViewById(R.id.start_intent_service);
startIntentService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_service:
Intent startintent = new Intent(this, MySercice.class);
startService(startintent);
break;
case R.id.stop_service:
Intent stopIntent = new Intent(this, MySercice.class);
stopService(stopIntent);
case R.id.bind_service:
Intent bindIntent = new Intent(this, MySercice.class);
bindService(bindIntent, Connection, BIND_AUTO_CREATE);
break;
case R.id.unbind_service:
unbindService(Connection);
break;
case R.id.start_intent_service:
Log.d("MainActivity", "Thread id is " + Thread.currentThread().getId());
Intent intentService = new Intent(this, MyIntentService.class);
startService(intentService);
break;
default:
break;
}
}
}
使用IntentService:
防止出现ANR的情况
package com.example.servicetest;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class MyIntentService extends IntentService {
// 调用父类的有参构造函数
public MyIntentService(String name) {
super("MyIntentService");
}
// 处理一些具体的逻辑,不用担心ANR问题
@Override
protected void onHandleIntent(Intent intent) {
// 打印当前线程的Id
Log.d("MyIntentService", "Thread id is " + Thread.currentThread().getId());
}
@Override
public void onDestroy() {
super.onDestroy();
// 证实服务是否停掉
Log.d("MyIntentService", "onDestory executed");
}
}
3.Service和Thread的区分
Thread:是程序执行的最小单元,时分配CPU的基本单位,执行异步操作。
Service:是Android的一种机制。运行的时候如果是Local Service,则Service是运行在主线程的main线程上;如果是Remote,则是运行在独立进程的main线程上。
所以他俩没有任何关系。
4.判断Service是否存在的方法:
public static boolean isServiceExisted(Context context, String className) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> sList = activityManager.getRunningServices(Integer.MAX_VALUE);
if (!(sList.size() > 0)) {
return false;
}
for (int i = 0; i < sList.size(); i++) {
RunningServiceInfo serviceInfo = sList.get(i);
ComponentName serviceName = serviceInfo.service;
if (serviceName.getClassName().equals(className)) {
return true;
}
}
return false;
}