今天实验的是Service。
Service的定义
Service是运行在后台的一段代码。它可以运行在它自己的进程,也可以运行在其他应用程序的上下文
(context)里面,这取决于自身的需要。其他的组件可以绑定到一个服务(Service)上面,通过远程过程调
用(RPC)来调用这个方法。例如:媒体播放器的服务,当用户退出媒体选择用户界面,仍然希望音乐可以
继续播放,这时就是由服务(Service)来保证当用户界面关闭时音乐继续播放的。
Service的生命周期
startService()后,即使调用startService()的进程结束了,Service 仍然还存在,知道有进程调用
stoptService(),或者Service 自己自杀(stopSelf())就没法了
bindService()后,Service 就和调用bindService()的进程同生共死,也就是说当调用bindService()的进
程死了,那么它bind 的Service 也要跟着被结束,当然期间也可以调用unbindService()让Service 结
束
两种方式混合使用时,比如说你startService()了,我bindService()了,那么只有你stoptService()了而
且我也unbindService()了,这个Service 才会被结束。
实验内容:定义一个Service,在一个Activity中打开。
实验过程:
1. 定义一个Service
package com.example.helloworld;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class FirstService extends Service
{
private MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent it,int i)
{
super.onStart(it, i);
Log.v("Service", "on");
}
@Override
public void onDestroy()
{
super.onDestroy();
Log.v("Service","stop");
player.stop();
}
}
如上,当Service被正确打开的时候,会打印出"on"。
2. 在AndroidManifest.xml中注册Service:
<service android:name="FirstService"/>
3. 在加载类中定义打开Service和销毁Service的方法:
Button button1=(Button) findViewById(R.id.button1);
Boolean playing_status=false;
button1.setOnClickListener(new View.OnClickListener()
{
boolean status=false;
public void onClick(View v)
{
Intent it=new Intent(Thd.this,FirstService.class);
startService(it);
}
});
如上,开始Service的方法被定义到一个button上,点击这个button会调用Service。
然后是加载类的onDestroy方法:
@Override
protected void onDestroy()
{
super.onDestroy();
stopService(new Intent("FirstService"));
}
如上,Service在Activity被销毁的时候停止。
4. 最后,发布,实验,成功