android学习笔记四——Service
2015-06-19 14:58
381 查看
service是运行后台的一段代码,并且和Activity不同,它不能直接和用户交互,也不能自行启动,对于service来说,主要用于在后台运行,比方说后台下载,后台播放音乐等,和Activity一样于oncreate后创建,ondestroy后销毁,一个service的启动有两种方式,一种是Context.StartService的方式来启动,这种方式启动服务后,该服务就和启动程序毫无关联了,只有在调用context.stopservice后,或者服务自行死亡后,该服务才会被销毁,第二种是通过Context.bindservice的方式绑定程序后启动服务,此时服务就和改程序绑定在一起了,当该程序死亡时服务也会被终结掉,这就是服务的基本概念
下面来介绍下服务的使用方式
1、首先要继承Service类并重写其中的onStart,onDestroy,onbind,onunbind,oncreate这几个方法
2.在入口程序中注册服务
3.使用startService或是bindService启动服务
(1)通过startservice启用服务时,android会首先调用oncreate方法创建服务,之后调用onstart启用服务,在调用stopservice结束服务时会自行调用ondestroy销毁服务,需要注意的是在服务被创建后,多次调用startservice并不会重复调用oncreate,除非服务销毁后,但多次调用startservice会多次调用onstart
(2)通过bindservice启用服务时,android会首先调用oncreate方法创建服务,之后调用onbind启用绑定服务,在调用unbindservice结束服务时会先调用onunbind解除绑定,在调用ondestroy销毁服务,需要注意的是在服务被创建后,多次调用bindservice并不会重复调用oncreate和onbind,除非该服务被销毁
下面重点介绍一下bindservice的启用方式
bindService一共有三个参数第一个参数为意图,第二个服务连接状态,第三个为标志
第一个参数的主要目的是为了定义要启动哪个服务,第二个参数就是指示连接该服务状态,第三个参数是定义其进行的方式
既然是第一个参数是intent,就需要先定义一个意图参数即
Intent intent=new Intent();然后和Activity一样通过setClass来指定要启动的服务
intent.setClass(ServiceDemo.this,MyService.class);
第二个参数是为了指示连接该服务状态
所以完整的调用方式如下
下面是一个方便理解服务进行过程的例子,提供了两种不同启用方式,本文中并没有介绍两种启动方式复合运用的场景,也可以通过下面的程序自行理解
servicedemo.Activity
action_servicedemo.xml
MyService.java
下面来介绍下服务的使用方式
1、首先要继承Service类并重写其中的onStart,onDestroy,onbind,onunbind,oncreate这几个方法
public class MyService extends Service { //定义log的标签 private static final String str="ServiceDemo"; private Mybind binder=new Mybind(); @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub Log.i(str,"start bind service"); return binder; } @Override public void onCreate() { // TODO Auto-generated method stub Log.i(str,"start create service"); super.onCreate(); } @Override public void onDestroy() { // TODO Auto-generated method stub Log.i(str,"start destroy service"); super.onDestroy(); } @SuppressWarnings("deprecation") @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub Log.i(str,"start service"); super.onStart(intent, startId); } @Override public boolean onUnbind(Intent intent) { // TODO Auto-generated method stub Log.i(str,"start unbind service"); return super.onUnbind(intent); } //此方法是为了可以在Acitity中获得服务的实例 public class Mybind extends Binder{ MyService getService(){ return MyService.this; } } }
2.在入口程序中注册服务
<service android:name=".MyService"></service>
3.使用startService或是bindService启动服务
(1)通过startservice启用服务时,android会首先调用oncreate方法创建服务,之后调用onstart启用服务,在调用stopservice结束服务时会自行调用ondestroy销毁服务,需要注意的是在服务被创建后,多次调用startservice并不会重复调用oncreate,除非服务销毁后,但多次调用startservice会多次调用onstart
(2)通过bindservice启用服务时,android会首先调用oncreate方法创建服务,之后调用onbind启用绑定服务,在调用unbindservice结束服务时会先调用onunbind解除绑定,在调用ondestroy销毁服务,需要注意的是在服务被创建后,多次调用bindservice并不会重复调用oncreate和onbind,除非该服务被销毁
下面重点介绍一下bindservice的启用方式
bindService一共有三个参数第一个参数为意图,第二个服务连接状态,第三个为标志
第一个参数的主要目的是为了定义要启动哪个服务,第二个参数就是指示连接该服务状态,第三个参数是定义其进行的方式
既然是第一个参数是intent,就需要先定义一个意图参数即
Intent intent=new Intent();然后和Activity一样通过setClass来指定要启动的服务
intent.setClass(ServiceDemo.this,MyService.class);
第二个参数是为了指示连接该服务状态
private ServiceConnection conn=new ServiceConnection(){ @Override //在连接成功时调用 public void onServiceConnected(ComponentName arg0, IBinder arg1) { // TODO Auto-generated method stub Log.i("ServiceDemo","connected Service"); } @Override //在服务连接失败时调用 public void onServiceDisconnected(ComponentName arg0) { // TODO Auto-generated method stub Log.i("ServiceDemo","disconnected Service"); } };
所以完整的调用方式如下
Intent intent=new Intent(); intent.setClass(ServiceDemo.this,MyService.class); private ServiceConnection conn=new ServiceConnection(){ @Override //在连接成功时调用 public void onServiceConnected(ComponentName arg0, IBinder arg1) { // TODO Auto-generated method stub Log.i("ServiceDemo","connected Service"); } @Override //在服务连接失败时调用 public void onServiceDisconnected(ComponentName arg0) { // TODO Auto-generated method stub Log.i("ServiceDemo","disconnected Service"); } }; mcontext.bindService(intent, conn, Context.BIND_AUTO_CREATE);
下面是一个方便理解服务进行过程的例子,提供了两种不同启用方式,本文中并没有介绍两种启动方式复合运用的场景,也可以通过下面的程序自行理解
servicedemo.Activity
package com.example.ui_demo; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class ServiceDemo extends Activity { private MyService mservice; private Button mButtonstart; private Button mButtonstop; private Button mButtonexit; private Button mButtonbind; private Button mButtonbindstop; private Context mcontext; private ServiceConnection conn=new ServiceConnection(){ @Override public void onServiceConnected(ComponentName arg0, IBinder arg1) { // TODO Auto-generated method stub Log.i("ServiceDemo","connected Service"); } @Override public void onServiceDisconnected(ComponentName arg0) { // TODO Auto-generated method stub Log.i("ServiceDemo","disconnected Service"); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_service_demo); setup(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.service_demo, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void setup(){ mcontext=ServiceDemo.this; mButtonstart=(Button) this.findViewById(R.id.startservice); mButtonstop=(Button) this.findViewById(R.id.stopservice); mButtonexit=(Button) this.findViewById(R.id.exitservice); mButtonbind=(Button) this.findViewById(R.id.bindservice); mButtonbindstop=(Button) this.findViewById(R.id.stopbindservice); Mybutton mbutton=new Mybutton(); mButtonstart.setOnClickListener(mbutton); mButtonstop.setOnClickListener(mbutton); mButtonexit.setOnClickListener(mbutton); mButtonbind.setOnClickListener(mbutton); mButtonbindstop.setOnClickListener(mbutton); } public class Mybutton implements OnClickListener{ @Override public void onClick(View vi ) { // TODO Auto-generated method stub if(vi==mButtonstart){ Intent intent=new Intent(); intent.setClass(ServiceDemo.this,MyService.class); mcontext.startService(intent); }else if(vi==mButtonstop){ Intent intent=new Intent(); intent.setClass(ServiceDemo.this,MyService.class); mcontext.stopService(intent); }else if(vi==mButtonexit){ ServiceDemo.this.finish(); }else if(vi==mButtonbind){ Intent intent=new Intent(); intent.setClass(ServiceDemo.this,MyService.class); mcontext.bindService(intent, conn, Context.BIND_AUTO_CREATE); }else if(vi==mButtonbindstop){ mcontext.unbindService(conn); } } } }
action_servicedemo.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.ui_demo.ServiceDemo" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <TableLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <TableRow> <Button android:id="@+id/startservice" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/stopservice" android:layout_below="@+id/stopservice" android:layout_column="1" android:layout_marginTop="16dp" android:text="启用服务" android:textSize="20sp" /> </TableRow> <TableRow> <Button android:id="@+id/stopservice" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginTop="24dp" android:text="停止服务" android:textSize="20sp" /> </TableRow> <TableRow> <Button android:id="@+id/bindservice" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginTop="24dp" android:text="启动绑定服务" android:textSize="20sp" /> </TableRow> <TableRow> <Button android:id="@+id/stopbindservice" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginTop="24dp" android:text="停止绑定服务" android:textSize="20sp" /> </TableRow> <TableRow> <Button android:id="@+id/exitservice" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_column="1" android:layout_marginTop="24dp" android:text="退出" android:textSize="20sp" /> </TableRow> </TableLayout> </RelativeLayout>
MyService.java
package com.example.ui_demo; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; public class MyService extends Service { //定义log的标签 private static final String str="ServiceDemo"; private Mybind binder=new Mybind(); @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub Log.i(str,"start bind service"); return binder; } @Override public void onCreate() { // TODO Auto-generated method stub Log.i(str,"start create service"); super.onCreate(); } @Override public void onDestroy() { // TODO Auto-generated method stub Log.i(str,"start destroy service"); super.onDestroy(); } @SuppressWarnings("deprecation") @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub Log.i(str,"start service"); super.onStart(intent, startId); } @Override public boolean onUnbind(Intent intent) { // TODO Auto-generated method stub Log.i(str,"start unbind service"); return super.onUnbind(intent); } public class Mybind extends Binder{ MyService getService(){ return MyService.this; } } }
相关文章推荐
- Android底层控制系统设置的命令集合
- Android 动画
- Android Studio 常用功能介绍
- Android 有道词典的简单实现方法介绍
- IIS 添加mime 支持 apk,exe,.woff,IIS MIME设置 ,Android apk下载的MIME 设置 苹果ISO .ipa下载mime 设置
- 【Android】四大组件+生命周期
- Android GPS学习笔记—JNI层实现
- android应用程序如何调用支付宝接口
- Android 百度地图2.4.2版本标注动画效果
- 一步步走进Android MaterialDesign
- android中ListView的Iterm无法点击
- Android Proguard returned with error code 1. See console 之注意事项
- 七海限时招募海盗,会写 Android 的海盗!
- 解决TextView强制换行
- android-进阶(3)-自定义view(1)
- Android Lollipop 新特性 - Palette
- Android Studio 初体验
- Android开发的十项注意
- Android 界面滑动实现---Scroller类 从源码和开发文档中学习(让你的布局动起来)
- android动态布局方法总结