有些程序不须要交互,在后台运行,并可长时间运行,不被操做系统杀死,这就是组件Serviceandroid
声明Service,新建class,MyService,扩展自Serviceide
AndroidManifest中配置, 在Application中添加Serivice,选择MySerivicethis
实际添加了一行:spa
<serviceandroid:name="MyService"></service>操作系统
添加二个按钮,启动Service和中止Serviceorm
<Button事件
android:id="@+id/btnStartService"ci
android:layout_width="wrap_content"get
android:layout_height="wrap_content"it
android:text="启动Servive"/>
<Button
android:id="@+id/btnStopService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="中止Service" />
4)代码中添加二按钮的定义:
private Button btnStartService,btnStopService;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStartService=(Button) findViewById(R.id.btnStartService);
btnStopService=(Button) findViewById(R.id.btnStopService);
}
5)添加两按钮的监听事件,鼠标放红线处,可自动生成:
(1)btnStartService.setOnClickListener(this);
(2)public class MainActivity extendsActionBarActivity implements OnClickListener
(3)@Override
publicvoid onClick(View v) {
//TODO Auto-generated method stub
}
6) 具体onClick内容:
@Override
publicvoid onClick(View v) {
//TODO Auto-generated method stub
switch(v.getId()){
case R.id.btnStartService:
break;
case R.id.btnStopService:
break;
default:
break;
}
7)启动Service,须要定义Intent,:
private Intent serviceIntent;
并建立实例:
serviceIntent=newIntent(this,MyService.class);
8) 在咱们的Service重写二方法,建立和销毁:
@Override
publicvoid onCreate(){
System.out.println("建立好了");
super.onCreate();
}
@Override
publicvoid onDestroy(){
System.out.println("被销毁了");
super.onDestroy();
}
9) 当前Activity销毁,Service还会再运行,经过设置->应用程序->运行的程序或服务,可看到。