Service的两种用法及其生命周期

时间:2023-12-23 19:25:07

先来一点基础知识:

  Service 是android的四大组件之一,与Activity同属于一个级别,它是运行在后台进行服务的组件(例如在后台播放的音乐,播放音乐的同时并不影响其他操作)。Service与Activity不同,Service没有界面。

  Service虽然在后台运行,但是却与Activity一样运行在主程序中,因此不可在Service中进行耗时的操作。如果需要耗时操作的时候,可以开启子线程来操作。

Service的两种用法及其生命周期:

1.startService   开启服务

2.bindService    绑定服务

Service的两种用法及其生命周期

上图是这两种用法的生命周期图:

1、启动方式:onCreate()->onStartCommand()->onStop()->onDestroy()
2、绑定方式:onCreate()->onBind()->onUnBind()->onDestroy()

Service的两种用法及其生命周期

启动服务:一般从活动中调用 startService() ==> 服务调用 onCreate()(创建时只调用一次)==>onStartCommand() (可调用多次)

停止服务:一般从活动中调用 stopService() ==> 服务调用 onDestroy() (只调用一次) 或 直接在服务中调用stopSelf()来停止,如果有绑定服务,得先解绑,才能停止服务

使用方法一:启动服务

例子:服务与Activity的交互

1.在MainActivity中设置两个Button,分别启动服务和停止服务。

 import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View; public class MainActivity extends ActionBarActivity {
int number=38;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void doButton(View v) {
Intent intent=new Intent();
switch (v.getId()) {
case R.id.button1:
intent.setAction("com.robin.testservice2.action");
intent.putExtra("number", number);
startService(intent);//启动服务
number++;
break; case R.id.button2:
intent.setAction("com.robin.testservice2.action");
stopService(intent);//停止服务
break;
default:
break;
}
}
}

2.建一个Service的子类----这是在执行每两秒cnt自动减1的操作,其代码如下:

 import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log; public class MyService extends Service{
protected static final String TAG = "robin debug";
MediaPlayer mp;
Thread printThread;
int cnt=-1;
boolean active=false;
@Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public void onCreate() {
Log.e(TAG,"service create");
super.onCreate();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG,"service start command");
cnt=intent.getIntExtra("number", -1);
active=true;
printThread=new Thread(){
@Override
public void run() {
while(active){
cnt--;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.e(TAG,"progress value--------->"+cnt);
}
}
};
printThread.start();
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
active=false;
super.onDestroy();
Log.e(TAG,"service destroy");
}
}

布局文件

 <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" > <TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" /> <Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginLeft="47dp"
android:layout_marginTop="24dp"
android:text="启动服务"
android:onClick="doButton"/> <Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="60dp"
android:text="停止服务"
android:onClick="doButton"/> </RelativeLayout>

以上的操作过程为,在Activity界面点击启动服务(startService(intent);)--->在MyService 中会执行

使用方法二:绑定服务

例子:Service与Activity之间进行通信

先来看看方法之间的调用顺序/过程:

Service的两种用法及其生命周期

上图中的代码:

ICount.java 类:

 package com.robin.testservice3;

 public interface ICount { //描述需要的行为(功能)
public int getCount();
public void setCount(int cnt);
}

MainActivity.java

 package com.robin.testservice3;

 import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView; public class MainActivity extends ActionBarActivity {
private ICount count;
private class MyConn implements ServiceConnection{ @Override
public void onServiceConnected(ComponentName name, IBinder binder) {
count=(ICount) binder;
} @Override
public void onServiceDisconnected(ComponentName name) {
count=null;
}
}
MyConn conn=new MyConn();
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent service=new Intent("com.robin.testservice3.action");
bindService(service, conn, BIND_AUTO_CREATE);
txt=(TextView)findViewById(R.id.result);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} public void doButton(View view ){
switch (view.getId()) {
case R.id.button1:
txt.setText("来自service子线程的计数值:"+count.getCount());
break;
case R.id.button2:
count.setCount(1000);
break;
default:
break;
}
}
@Override
protected void onDestroy() {
unbindService(conn);
super.onDestroy();
}
}

MyService.java

 package com.robin.testservice3;

 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{
protected static final String TAG = "robin debug";
private boolean active=false;
private int cnt=0;
private class MyBinder extends Binder implements ICount{ @Override
public int getCount() {
return cnt;
}
@Override
public void setCount(int cnt) {
MyService.this.cnt=cnt;
}
}
MyBinder binder=new MyBinder(); @Override
public IBinder onBind(Intent intent) {
return binder;
} @Override
public void onCreate() {
new Thread(new Runnable() { @Override
public void run() {
active=true;
while(active){
cnt++;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.e(TAG,"service thread :cnt----->"+cnt); }
}
}).start();
super.onCreate();
}
@Override
public void onDestroy() {
Log.e(TAG,"service call onDestroy");
active=false;
super.onDestroy();
}
}

布局文件:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="测试绑定使用service" /> <Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="读service端子线程的计数值"
android:onClick="doButton"/> <Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="修改service端子线程的计数值"
android:onClick="doButton"/> <TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" /> </LinearLayout>

Service的两种用法及其生命周期