Service是一个应用程序组件,没有界面,在后台运行和Activity是一个级别的。通常用来处理一些耗时较长的操作。可以使用Service更新ContentProvider,播放MP3,网络连接,发送Intent以及启动系统的通知等等。
Service不是一个单独的进程
Service不是一个线程,(一个进程有多个线程)
启动Service:
—Context.startSevice();
停止Service
—Context.stopService();
FirstService.java中的代码:
//创建了一个服务类
public class FirstService extends Service {
//重载onBind()函数,该函数在Service被绑定后调用,能够返回Service对象实例
@Override
public IBinder onBind(Intent intent) {
return null;
}
//当创建一个Service对象之后,首先会调用这个函数
public void onCreate() {
super.onCreate();
System.out.println("Service onCreate");
}
//主要功能放在这里
public int onStartCommand(Intent intent,int flags,int startId){
System.out.println("flags-->"+flags);
System.out.println("startld-->"+startId);
System.out.println("Service onStartCommand");
return START_NOT_STICKY;
}
//关闭Service,释放资源。
public void onDestroy(){
System.out.println("Service onDestroy");
super.onDestroy();
}
}
MainActivity.java中的代码:
public class MainActivity extends Activity {
//创建两个按钮
private Button startServiceButton=null;
private Button stopServiceButton=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startServiceButton=(Button)findViewById(R.id.startService);
//添加监听
startServiceButton.setOnClickListener(new StartServiceListener());
stopServiceButton=(Button)findViewById(R.id.stopService);
stopServiceButton.setOnClickListener(new StopServiceListener());
}
//监听类
class StartServiceListener implements OnClickListener{
@Override
public void onClick(View v) {
//创建intent,并为它指定当前的应用程序上下文以及要启动的service
Intent intent=new Intent();
intent.setClass(MainActivity.this,FirstService.class);
//传递一个intent对象
startService(intent);
}
}
class StopServiceListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.setClass(MainActivity.this,FirstService.class);
stopService(intent);
}
}
}
在AndroidManifest.xml中注册service:
<service android:name=".FirstService"></service>