Android中Service的使用

书史足自悦,安用勤与劬。这篇文章主要讲述Android中Service的使用相关的知识,希望能为你提供帮助。
我个人的理解是:我们平时使用的android系统的app的后台应用,就是这个原理
可以利用Service实现程序在后台运行,依照这个原理,可以通过Service来实现关键代码的运行与实现。
《一》下面大体说一下我在极客学院跟着视频做的一个Service的小实现
1,首先点击左上角file-> new往下拉,看到一个Service,创建MyService.java
这个就是我们的Service服务。
后续可以在这其中添加想要在后台运行的关键代码等。
2,首先创建项目后,在layout或中的xml中添加两个按钮btnStartSevice和btnStopSevice
程序中的Sevice是拼写错误,应该是Service,如果路人看到请不要打脸。。。

< ?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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="examples.ouc.com.learnsevice2.MainActivity"> < TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> < Button android:text="Start Sevice" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btnStartSevice" /> < Button android:text="Stop Sevice" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btnStopSevice" /> < /LinearLayout>

3,然后在MainActivity中配置这两个按钮。
1 package examples.ouc.com.learnsevice2; 2 3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 8 public class MainActivity extends AppCompatActivity { 9 10private Intent intent; 11@Override 12protected void onCreate(Bundle savedInstanceState) { 13super.onCreate(savedInstanceState); 14setContentView(R.layout.activity_main); 15 16//通过intent可以实现代码复用 17intent =new Intent(MainActivity.this,MyService.class); 18 19//简单的对两个按钮设置监听器。 20findViewById(R.id.btnStartSevice).setOnClickListener(new View.OnClickListener() { 21@Override 22public void onClick(View v) { 23 24//开始服务 25startService(intent); 26} 27}); 28 29findViewById(R.id.btnStopSevice).setOnClickListener(new View.OnClickListener() { 30@Override 31public void onClick(View v) { 32 33//停止服务 34stopService(intent); 35} 36}); 37} 38 }

4,在MyService中进行相应的操作配置。
1 package examples.ouc.com.learnsevice2; 2 3 import android.app.Service; 4 import android.content.Intent; 5 import android.os.IBinder; 6 7 public class MyService extends Service { 8public MyService() { 9} 10 11@Override 12public IBinder onBind(Intent intent) { 13// TODO: Return the communication channel to the service. 14throw new UnsupportedOperationException("Not yet implemented"); 15} 16 17@Override 18//重写的onStartCommand在startService()运行时自动运行。 19public int onStartCommand(Intent intent, int flags, int startId) { 20new Thread(){ 21@Override 22 23public void run() { 24super.run(); 25 26//通过设置输出一行代码来判断服务是否一直在运行中。 27while(true){ 28System.out.println("sevice is running..."); 29try { 30 31//间隔2s输出一次 32sleep(2000); 33} catch (InterruptedException e) { 34e.printStackTrace(); 35}} 36} 37}.start(); 38return super.onStartCommand(intent, flags, startId); 39} 40 }

5,最后,我们就可以发布到我们的AVD上进行运行了,点击开始服务,就可以在AS下面run运行状态框中看到
每隔两秒钟,就打印一行  sevice is running...

这个实例很简单,只是实现Service的后台运行,实际项目中,这个功能是十分重要的,希望自己日后用到时,能够想起来。。。菜鸟立flag
 
《二》service的绑定与声明周期
我们对上面的代码进行一些改动
1,首先,添加两个按钮,指示绑定服务,和解除绑定服务
Android中Service的使用

文章图片
Android中Service的使用

文章图片
1 < ?xml version="1.0" encoding="utf-8"?> 2 < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3xmlns:tools="http://schemas.android.com/tools" 4android:id="@+id/activity_main" 5android:layout_width="match_parent" 6android:layout_height="match_parent" 7android:paddingBottom="@dimen/activity_vertical_margin" 8android:paddingLeft="@dimen/activity_horizontal_margin" 9android:paddingRight="@dimen/activity_horizontal_margin" 10android:paddingTop="@dimen/activity_vertical_margin" 11android:orientation="vertical" 12tools:context="examples.ouc.com.learnsevice2.MainActivity"> 13 14< TextView 15android:layout_width="wrap_content" 16android:layout_height="wrap_content" 17android:text="Hello World!" /> 18 19< Button 20android:text="Start Sevice" 21android:layout_width="match_parent" 22android:layout_height="wrap_content" 23android:id="@+id/btnStartSevice" /> 24 25< Button 26android:text="Stop Sevice" 27android:layout_width="match_parent" 28android:layout_height="wrap_content" 29android:id="@+id/btnStopSevice" /> 30< Button 31android:text="Bind Sevice" 32android:layout_width="match_parent" 33android:layout_height="wrap_content" 34android:id="@+id/btnBindSevice" /> 35< Button 36android:text="Unbind Sevice" 37android:layout_width="match_parent" 38android:layout_height="wrap_content" 39android:id="@+id/btnUnbindSevice" /> 40 < /LinearLayout>

View Code2,然后我们在MainActivity中进行配置
Android中Service的使用

文章图片
Android中Service的使用

文章图片
1 package examples.ouc.com.learnsevice2; 2 3 import android.content.ComponentName; 4 import android.content.Context; 5 import android.content.Intent; 6 import android.content.ServiceConnection; 7 import android.os.IBinder; 8 import android.support.v7.app.AppCompatActivity; 9 import android.os.Bundle; 10 import android.view.View; 11 12 public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection { 13 14private Intent intent; 15@Override 16protected void onCreate(Bundle savedInstanceState) { 17super.onCreate(savedInstanceState); 18setContentView(R.layout.activity_main); 19 20//通过intent可以实现代码复用 21intent =new Intent(MainActivity.this,MyService.class); 22 23//简单的对两个按钮设置监听器。 24findViewById(R.id.btnStartSevice).setOnClickListener(this); 25 26findViewById(R.id.btnStopSevice).setOnClickListener(this); 27 28findViewById(R.id.btnBindSevice).setOnClickListener(this); 29findViewById(R.id.btnUnbindSevice).setOnClickListener(this); 30} 31 32@Override 33public void onClick(View v) { 34switch (v.getId()){ 35case R.id.btnStartSevice: 36startService(intent); 37break; 38case R.id.btnStopSevice: 39stopService(intent); 40break; 41case R.id.btnBindSevice: 42//bindService(Intent参数,服务的连接,服务的状态) 43bindService(intent,this,Context.BIND_AUTO_CREATE); 44break; 45case R.id.btnUnbindSevice: 46unbindService(this); 47break; 48} 49} 50 51@Override 52//服务被绑定成功后执行 53public void onServiceConnected(ComponentName name, IBinder service) { 54System.out.println("Service connected!"); 55} 56 57@Override 58//服务所在进城崩溃或者北杀掉时候执行。 59public void onServiceDisconnected(ComponentName name) { 60 61} 62 }

View Code3,然后在MyService中进行一些改动,方便我们查看是否什么时候创建与销毁。
Android中Service的使用

文章图片
Android中Service的使用

文章图片
1 package examples.ouc.com.learnsevice2; 2 3 import android.app.Service; 4 import android.content.Intent; 5 import android.os.Binder; 6 import android.os.IBinder; 7 8 public class MyService extends Service { 9 10//通过设定一个flag,判断service是否仍然在运行 11private boolean serviceRunning = false; 12public MyService() { 13} 14 15@Override 16public IBinder onBind(Intent intent) { 17// TODO: Return the communication channel to the service. 18//throw new UnsupportedOperationException("Not yet implemented"); 19return new Binder(); 20} 21 22@Override 23//重写的onStartCommand在startService()运行时自动运行。 24public int onStartCommand(Intent intent, int flags, int startId) { 25System.out.println("onStartCommand"); 26new Thread(){ 27@Override 28 29public void run() { 30super.run(); 31 32//通过设置输出一行代码来判断服务是否一直在运行中。 33//只有service仍在运行时,才会输出在这句话 34while(serviceRunning){ 35System.out.println("sevice is running..."); 36try { 37 38//间隔2s输出一次 39sleep(2000); 40} catch (InterruptedException e) { 41e.printStackTrace(); 42}} 43} 44}.start(); 45return super.onStartCommand(intent, flags, startId); 46} 47 48@Override 49public void onCreate() { 50super.onCreate(); 51serviceRunning = true; 52System.out.println("service create!"); 53} 54 55@Override 56public void onDestroy() { 57super.onDestroy(); 58System.out.println("service destory!"); 59serviceRunning = false; 60} 61 }

View Code4,然后我们可以发布,执行。
【Android中Service的使用】 

    推荐阅读