189 8069 5689

10天学通Android开发(2-2)-核心组件Service创建-创新互联

有些程序不需要交互,在后台运行,并可长时间运行,不被操作系统杀死,这就是组件Service

创新互联公司专注于网站建设,为客户提供做网站、网站设计、网页设计开发服务,多年建网站服务经验,各类网站都可以开发,品牌网站建设,公司官网,公司展示网站,网站设计,建网站费用,建网站多少钱,价格优惠,收费合理。
  1. 声明Service,新建class,MyService,扩展自Service

  2. AndroidManifest中配置, 在Application中添加Serivice,选择MySerivice

    实际添加了一行:

  3. 添加二个按钮,启动Service和停止Service

           android:id="@+id/btnStartService"

           android:layout_width="wrap_content"

           android:layout_height="wrap_content"

           android:text="启动Servive"/>

       

           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还会再运行,通过设置->应用程序->运行的程序或服务,可看到。

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享标题:10天学通Android开发(2-2)-核心组件Service创建-创新互联
本文链接:http://cdxtjz.cn/article/djojps.html

其他资讯