service继承于service
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
每一个服务都需要在 AndroidManifest.xml 文件中进行注册才能生效, 这是 Android 四大组件共有的特点。
启动和停止service
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent); // 启动服务
break;
case R.id.stop_service:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent); // 停止服务
break;
default: break;
} }
activity和service的绑定
public class MainActivity extends Activity implements OnClickListener {
private Button startService;
private Button stopService;
private Button bindService;
private Button unbindService;
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) { }
@Override
public void onServiceConnected(ComponentName name, IBinder service) {}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
⋯⋯
bindService = (Button) findViewById(R.id.bind_service);
unbindService = (Button) findViewById(R.id.unbind_service);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) { ⋯⋯
case R.id.bind_service:
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE); // 绑定服务
break;
case R.id.unbind_service:
unbindService(connection); // 解绑服务
break;
default: break;
}
}
}
使用前台服务
public class MyService extends Service {
@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);
}
IntentService
在运行完毕后确实自动停止了。
集开启线程和自动停止于一身
service和thread的区别
Service只是从逻辑上表示一个用来执行”longer-running”的”后台”任务或功能的”application component”。
为什么强调说”longer running”的”component”?
这里是和Activity这种活跃周期相对短暂的component对比而言。一旦用户切换到其他应用,当前Activity就必须pause, stop甚至被destroy,不能在后台处理其他事务。
需要强调的事,严格来说你仍然可以在activity里创建自己的worker thread或async task之类做后台的事情,但这样做没有任何保障——因为一旦你所有的activity都被切换到了后台,系统随时可能kill掉你的process,你的后台任务随时可能悄无声息的死掉。
通过在manifest里声明Service,把需要后台相对长期运行的逻辑放在Service里,你便获得了这样的保障:只要系统内存不是极端不够用,你的Service一定不会被kill掉。对系统而言,当看到一个进程里有Service在运行,这个进程就具有较高的优先级,会在内存不足被杀的行列里排得比较靠后。