android开发步步为营之37:四大组件之Service(上)通过startService(intent)启动
2014-09-24 14:39
573 查看
写过windows service的人都知道,windows service是一个运行在后台看不见的服务,它默默地处理着业务,android 的service也一样,它运行在后台,前台是看不见的,我们可以理解为它是一个不可见的activity。比如常见音乐、广播电台播放器,打开后,它就在后台运行了,这个时候我们又可以去做其他事情,比如玩游戏,看书,发短信等等。
Service是android 系统中的一种组件,它跟Activity的级别差不多,但是他不能自己运行,只能后台运行,并且可以和其他组件进行交互。Service的启动有两种方式:context.startService() 和 context.bindService()。
使用context.startService() 启动Service是会会经历:
context.startService() ->onCreate()- >onStart()->Service running
context.stopService() | ->onDestroy() ->Service stop
如果Service还没有运行,则android先调用onCreate()然后调用onStart();如果Service已经运行,则只调用onStart(),所以一个Service的onStart方法可能会重复调用多次。
stopService的时候直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行。该Service的调用者再启动起来后可以通过stopService关闭Service。
所以调用startService的生命周期为:onCreate --> onStart(可多次调用) --> onDestroy
使用使用context.bindService()启动Service会经历:
context.bindService()->onCreate()->onBind()->Service running
onUnbind() -> onDestroy() ->Service stop
onBind将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,Srevice就会调用onUnbind->onDestroy相应退出。
所以调用bindService的生命周期为:onCreate --> onBind(只一次,不可多次绑定) --> onUnbind --> onDestory。
在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次
这一篇,我通过context.startService()来启动我们的音乐播放服务,本篇范例,写的就是一个音乐播放器,播放器播放音乐,暂停、停止、关闭都将调用一个音乐播放服务MusicService。
开始我们的范例:
第一步:设计简单的播放器页面musicview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="wrap_content" android:id="@+id/btnclose" android:text="@string/close" android:layout_height="wrap_content" android:layout_below="@+id/btnstop" android:layout_alignParentLeft="true" android:layout_marginTop="17dp" android:layout_alignParentRight="true"></Button>
<Button android:layout_width="wrap_content" android:id="@+id/btnpause" android:text="@string/pause" android:layout_height="wrap_content" android:layout_below="@+id/btnplay" android:layout_alignParentLeft="true" android:layout_marginTop="14dp" android:layout_alignParentRight="true"></Button>
<TextView android:layout_width="wrap_content" android:text="@string/musicplayer" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true"></TextView>
<Button android:layout_width="wrap_content" android:id="@+id/btnstop" android:text="@string/stop" android:layout_height="wrap_content" android:layout_below="@+id/btnpause" android:layout_alignParentLeft="true" android:layout_marginTop="16dp" android:layout_alignParentRight="true"></Button>
<Button android:layout_width="wrap_content" android:id="@+id/btnplay" android:text="@string/play" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_alignParentLeft="true" android:layout_marginTop="15dp" android:layout_alignParentRight="true"></Button>
</RelativeLayout>
第二步、设计MusicService.java
/**
*
*/
package Test.HelloWorld;
import java.io.IOException;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
/**
* @author zhuzhifei
*
*/
public class MusicService extends Service {
private static final String TAG = "MusicService";//定义日志tag
private MediaPlayer mediaPlayer;//定义音乐播放器
/*
* (non-Javadoc)
*
* @see android.app.Service#onBind(android.content.Intent)
*/
//绑定服务
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
//创建服务
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.v(TAG, "onCreate");
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(this, R.raw.ohprettywoman); //res/raw文件里面放一个mp3文件ohprettywoman
mediaPlayer.setLooping(false);
}
}
//销毁服务
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.v(TAG, "onDestroy");
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
//启动服务
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.v(TAG, "onStart");
if (intent != null) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
int op = bundle.getInt("op");
switch (op) {
case 1:
play();
break;
case 2:
pause();
break;
case 3:
stop();
break;
}
}
}
}
//播放器播放音乐
public void play() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
//暂停播放
public void pause() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
//停止播放
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
try {
// 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
mediaPlayer.prepare();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
第三步、设计Activity MusicServiceActivity.java
package Test.HelloWorld;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MusicServiceActivity extends Activity implements OnClickListener {
private static final String TAG = "PlayMusic";
private Button btnplay;
private Button btnpause;
private Button btnstop;
private Button btnclose;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.musicview);
btnplay = (Button) findViewById(R.id.btnplay);
btnpause = (Button) findViewById(R.id.btnpause);
btnstop = (Button) findViewById(R.id.btnstop);
btnclose = (Button) findViewById(R.id.btnclose);
btnplay.setOnClickListener(this);
btnpause.setOnClickListener(this);
btnstop.setOnClickListener(this);
btnclose.setOnClickListener(this);
}
//定义按钮事件
@Override
public void onClick(View v) {
int op = -1;
Intent intent = new Intent("Test.HelloWorld.MusicService");
// 用广播
// Intent intent = new Intent("org.allin.android.musicReceiver");
switch (v.getId()) {
case R.id.btnplay:
Log.d(TAG, "onClick: playing muic");
op = 1;
break;
case R.id.btnpause:
Log.d(TAG, "onClick: pausing music");
op = 2;
break;
case R.id.btnstop:
Log.d(TAG, "onClick: stoping music");
op = 3;
break;
case R.id.btnclose:
Log.d(TAG, "onClick: close");
op = 4;
stopService(intent);
this.finish();
break;
}
// 给意图传递参数
Bundle bundle = new Bundle();
bundle.putInt("op", op);
intent.putExtras(bundle);
// 第一种方法startService来启动service
startService(intent);
}
}
第四步、AndroidManifest.xml注册activity和service
<service android:enabled="true" android:name=".MusicService">
<intent-filter>
<action android:name="Test.HelloWorld.MusicService" />
</intent-filter>
</service>
<activity android:name=".MusicServiceActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
第五步、运行效果
Service是android 系统中的一种组件,它跟Activity的级别差不多,但是他不能自己运行,只能后台运行,并且可以和其他组件进行交互。Service的启动有两种方式:context.startService() 和 context.bindService()。
使用context.startService() 启动Service是会会经历:
context.startService() ->onCreate()- >onStart()->Service running
context.stopService() | ->onDestroy() ->Service stop
如果Service还没有运行,则android先调用onCreate()然后调用onStart();如果Service已经运行,则只调用onStart(),所以一个Service的onStart方法可能会重复调用多次。
stopService的时候直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行。该Service的调用者再启动起来后可以通过stopService关闭Service。
所以调用startService的生命周期为:onCreate --> onStart(可多次调用) --> onDestroy
使用使用context.bindService()启动Service会经历:
context.bindService()->onCreate()->onBind()->Service running
onUnbind() -> onDestroy() ->Service stop
onBind将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,Srevice就会调用onUnbind->onDestroy相应退出。
所以调用bindService的生命周期为:onCreate --> onBind(只一次,不可多次绑定) --> onUnbind --> onDestory。
在Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次
这一篇,我通过context.startService()来启动我们的音乐播放服务,本篇范例,写的就是一个音乐播放器,播放器播放音乐,暂停、停止、关闭都将调用一个音乐播放服务MusicService。
开始我们的范例:
第一步:设计简单的播放器页面musicview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="wrap_content" android:id="@+id/btnclose" android:text="@string/close" android:layout_height="wrap_content" android:layout_below="@+id/btnstop" android:layout_alignParentLeft="true" android:layout_marginTop="17dp" android:layout_alignParentRight="true"></Button>
<Button android:layout_width="wrap_content" android:id="@+id/btnpause" android:text="@string/pause" android:layout_height="wrap_content" android:layout_below="@+id/btnplay" android:layout_alignParentLeft="true" android:layout_marginTop="14dp" android:layout_alignParentRight="true"></Button>
<TextView android:layout_width="wrap_content" android:text="@string/musicplayer" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true"></TextView>
<Button android:layout_width="wrap_content" android:id="@+id/btnstop" android:text="@string/stop" android:layout_height="wrap_content" android:layout_below="@+id/btnpause" android:layout_alignParentLeft="true" android:layout_marginTop="16dp" android:layout_alignParentRight="true"></Button>
<Button android:layout_width="wrap_content" android:id="@+id/btnplay" android:text="@string/play" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_alignParentLeft="true" android:layout_marginTop="15dp" android:layout_alignParentRight="true"></Button>
</RelativeLayout>
第二步、设计MusicService.java
/**
*
*/
package Test.HelloWorld;
import java.io.IOException;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
/**
* @author zhuzhifei
*
*/
public class MusicService extends Service {
private static final String TAG = "MusicService";//定义日志tag
private MediaPlayer mediaPlayer;//定义音乐播放器
/*
* (non-Javadoc)
*
* @see android.app.Service#onBind(android.content.Intent)
*/
//绑定服务
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
//创建服务
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.v(TAG, "onCreate");
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(this, R.raw.ohprettywoman); //res/raw文件里面放一个mp3文件ohprettywoman
mediaPlayer.setLooping(false);
}
}
//销毁服务
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.v(TAG, "onDestroy");
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
//启动服务
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.v(TAG, "onStart");
if (intent != null) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
int op = bundle.getInt("op");
switch (op) {
case 1:
play();
break;
case 2:
pause();
break;
case 3:
stop();
break;
}
}
}
}
//播放器播放音乐
public void play() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
//暂停播放
public void pause() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
//停止播放
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
try {
// 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
mediaPlayer.prepare();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
第三步、设计Activity MusicServiceActivity.java
package Test.HelloWorld;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MusicServiceActivity extends Activity implements OnClickListener {
private static final String TAG = "PlayMusic";
private Button btnplay;
private Button btnpause;
private Button btnstop;
private Button btnclose;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.musicview);
btnplay = (Button) findViewById(R.id.btnplay);
btnpause = (Button) findViewById(R.id.btnpause);
btnstop = (Button) findViewById(R.id.btnstop);
btnclose = (Button) findViewById(R.id.btnclose);
btnplay.setOnClickListener(this);
btnpause.setOnClickListener(this);
btnstop.setOnClickListener(this);
btnclose.setOnClickListener(this);
}
//定义按钮事件
@Override
public void onClick(View v) {
int op = -1;
Intent intent = new Intent("Test.HelloWorld.MusicService");
// 用广播
// Intent intent = new Intent("org.allin.android.musicReceiver");
switch (v.getId()) {
case R.id.btnplay:
Log.d(TAG, "onClick: playing muic");
op = 1;
break;
case R.id.btnpause:
Log.d(TAG, "onClick: pausing music");
op = 2;
break;
case R.id.btnstop:
Log.d(TAG, "onClick: stoping music");
op = 3;
break;
case R.id.btnclose:
Log.d(TAG, "onClick: close");
op = 4;
stopService(intent);
this.finish();
break;
}
// 给意图传递参数
Bundle bundle = new Bundle();
bundle.putInt("op", op);
intent.putExtras(bundle);
// 第一种方法startService来启动service
startService(intent);
}
}
第四步、AndroidManifest.xml注册activity和service
<service android:enabled="true" android:name=".MusicService">
<intent-filter>
<action android:name="Test.HelloWorld.MusicService" />
</intent-filter>
</service>
<activity android:name=".MusicServiceActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
第五步、运行效果
相关文章推荐
- android开发步步为营之36:四大组件之Service(中)通过bindService启动
- Android开发之通过Intent启动其他App的Service
- 【Android四大组件之Service】(三)Service中startService与bindService的区别
- android开发步步为营之30:四大组件之Activity
- android四大组件之Service和子类IntentService
- Android开发四大组件---Service详解
- 01 Android应用的构成 四大组件 Activity, Intent Receiver , Service , Content Provider
- android开发步步为营之60:IntentService与Service的区别
- Android的四大组件之二--BroadcastReceiver(相关内容,开机启动Service)
- Intent启动系统组件(activity,service,BroadReceiver)-android学习之旅(四十九)
- Intent启动系统组件(activity,service,BroadReceiver)-android学习之旅(四十九)
- Android开发四大组件---Service详解
- android四大组件之一Service的startService()与bindService()区别?
- Android开发四大组件---Service详解
- Android的四大组件之二--BroadcastReceiver(相关内容,开机启动Service)
- Android 开发之四大组件 --- Service
- Android的四大组件之二--BroadcastReceiver(相关内容,开机启动Service)
- Android开发四大组件之Service(实例篇)
- Android四大组件之服务-Service 原理和应用开发详解
- Android开发之四大组件——Service