码迷,mamicode.com
首页 > 移动开发 > 详细

《Android笔记3.7》 认识 Android Service

时间:2015-08-05 16:17:32      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

课程背景:
Service 是 Android 四大基本组件之一,是无界面的应用程序,可以长期在后台运行,在实际工作中非常重要,比如接收推送消息、在锁屏状态下侦听传感器信息。

核心内容:
1.启动Service
2.绑定Service

使用 Service

新建Service文件:MyService.java

技术分享

 

重写Serivce的启动函数:

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        new Thread(){
            @Override
            public void run() {
                super.run();
                while (true) {
                    System.out.println("服务正在运行...");

                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        return super.onStartCommand(intent, flags, startId);
    }

 

启动Service:

startService(new Intent(MainActivity.this, MyService.class));

停止Service:

//一个程序中Service只能存在一个,新创建一个Intent并不影响最终效果
stopService(new Intent(MainActivity.this, MyService.class));

 

《Android笔记3.7》 认识 Android Service

标签:

原文地址:http://www.cnblogs.com/woodk/p/4704984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!