本文主要是介绍基础篇1.9 Service简介,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
基础篇1.9 Service简介
一、service是什么
1、 Service是应用程序组件,和Activity属于同一层次。
2、 Service没有图形化界面。
3、 Service通常用来处理一些耗时比较长的操作。如下载等。
4、 可以使用Service更新ContentProvider,发送Intent以及启动系统通知等。
二、Service生命周期
1、 启动Service:Context.startService()
2、 停止Service:Context.stopService()
三、应用举例:
定义MainActivity:
package com.solidwang.service_01;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public classMainActivity extends Activity {
private Button startService;
private Button stopService;
@Override
protected void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService = (Button)findViewById(R.id.startService);
stopService = (Button)findViewById(R.id.stopService);
startService.setOnClickListener(newStartServiceListener());
stopService.setOnClickListener(new StopServiceListener());
}
//启动Service
class StartServiceListener implements OnClickListener{
@Override
public void onClick(View v) {
Intentintent = newIntent();
intent.setClass(MainActivity.this, MyService.class);
startService(intent);
}
}
//停止Service
class StopServiceListener implements OnClickListener{
@Override
public void onClick(View v) {
Intentintent = newIntent();
intent.setClass(MainActivity.this, MyService.class);
stopService(intent);
}
}
}
MyService中重写Service的方法:
packagecom.solidwang.service_01;
importandroid.app.Service;
importandroid.content.Intent;
importandroid.os.IBinder;
publicclass MyService extends Service {
//初次启动Service的时候调用
//如果Service已经处于启动状态,再次启动启动不会再执行onCreate
@Override
public void onCreate() {
System.out.println("---onCreate---");
}
//执行完毕onCreate后执行onStartCommand
@Override
public int onStartCommand(Intentintent, int flags, int startId) {
System.out.println("intent="+ intent + ", flags=" + flags + ", startId=" + startId);
return START_NOT_STICKY;
}
//停止Service时执行
@Override
public void onDestroy() {
System.out.println("---onDestroy---");
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated methodstub
return null;
}
}
在AndroidManifest.xml中注册:
<service android:name=".MyService" />
运行结果:
这篇关于基础篇1.9 Service简介的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!