首页 > 移动平台 > 详细

android编程如何让程序后台运行

时间:2015-03-24 01:45:26      阅读:316      评论:0      收藏:0      [点我收藏+]

通过android的四大组件之一的service来实现后台运行,类似Windows上的服务。

1、Android上的service有两种启动方式(或者说两种方法实现service)

 ①startService()和bindService() ,有区别。

2、简单的使用Service步骤(startService()):

①建立service的子类,重写onStartCommand()。(当服务启动的时候会调用该方法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public  class  HelloService  extends  Service {
  
  @Override
   public  void  onCreate() {
   }
 
   //这个函数在低版本中使用的是onStart(),onStart()在高版本中已经过时了。
   @Override
   public  int  onStartCommand(Intent intent,  int  flags,  int  startId) {
   }
 
  @Override
   public  void  onDestroy() {
   }
}

②在清单文件中声明Service组件

1
2
3
4
5
6
7
< application >
            < service  android:name = "HelloService" >
                 < intent-fiter >
                     < action  android:name = "xxxxx" >
                 </ intent-fiter >
             </ service >
</ application >

③在Activity等调用startService(intent);启动你的Service

1
2
3
Intent intent =  new  Intent( "xxxxx" );
//还可以使用Intent intent = new Intent(activity.this,HelloService.class);
startService(intent);

注:两种方法各有不同,具体请看官方API:

http://developer.android.com/guide/components/services.html

android编程如何让程序后台运行

原文:http://my.oschina.net/airship/blog/390620

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!