码迷,mamicode.com
首页 > 其他好文 > 详细

Service(一):认识service

时间:2015-10-13 21:11:41      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

     Activity是与用户打交道的,而Service是在后台运行的。

     这个程序介绍了下如何启动和停止一个Service,以及在后台打印消息,我添加了一些注释。

 

    在activity_main中将布局改为线性布局,方向改为垂直并添加两个按钮,

    

技术分享
 android:orientation="vertical"
<Button
        android:layout_width="69dp"
        android:layout_height="wrap_content"
        android:text="启动服务"
        android:id="@+id/btnStartService"
        android:layout_weight="0.06" />
    <Button
        android:layout_width="69dp"
        android:layout_height="wrap_content"
        android:text="停止服务"
        android:id="@+id/btnStopService"
        android:layout_weight="0.06" />
View Code

 

     在MainActivity中

     

技术分享
 intent = new Intent(MainActivity.this,MyService.class);//启动另一个活动

        findViewById(R.id.btnStartService).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(intent);
            }
        });

        findViewById(R.id.btnStopService).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(intent);
            }
        });
View Code

   

    在MyService中,负责在后台打印消息,注意如何创建一个线程:

   

技术分享
 public int onStartCommand(Intent intent, int flags, int startId) {
        //startService()启动时,这个函数自动启动
        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);
    }
View Code

 

具体参考: http://www.jikexueyuan.com/course/683.html

     

Service(一):认识service

标签:

原文地址:http://www.cnblogs.com/573177885qq/p/4875738.html

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