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

Android中Service的使用

时间:2016-10-20 21:31:34      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:

我个人的理解是:我们平时使用的android系统的app的后台应用,就是这个原理

可以利用Service实现程序在后台运行,依照这个原理,可以通过Service来实现关键代码的运行与实现。

《一》下面大体说一下我在极客学院跟着视频做的一个Service的小实现

1,首先点击左上角file->new往下拉,看到一个Service,创建MyService.java

  这个就是我们的Service服务。

  后续可以在这其中添加想要在后台运行的关键代码等。

2,首先创建项目后,在layout或中的xml中添加两个按钮btnStartSevice和btnStopSevice

程序中的Sevice是拼写错误,应该是Service,如果路人看到请不要打脸。。。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="examples.ouc.com.learnsevice2.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:text="Start Sevice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnStartSevice" />

    <Button
        android:text="Stop Sevice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnStopSevice" />
</LinearLayout>

3,然后在MainActivity中配置这两个按钮。

 1 package examples.ouc.com.learnsevice2;
 2 
 3 import android.content.Intent;
 4 import android.support.v7.app.AppCompatActivity;
 5 import android.os.Bundle;
 6 import android.view.View;
 7 
 8 public class MainActivity extends AppCompatActivity {
 9 
10     private Intent intent;
11     @Override
12     protected void onCreate(Bundle savedInstanceState) {
13         super.onCreate(savedInstanceState);
14         setContentView(R.layout.activity_main);
15         
16         //通过intent可以实现代码复用
17         intent =new Intent(MainActivity.this,MyService.class);
18         
19         //简单的对两个按钮设置监听器。
20         findViewById(R.id.btnStartSevice).setOnClickListener(new View.OnClickListener() {
21             @Override
22             public void onClick(View v) {
23                 
24                 //开始服务
25                 startService(intent);
26             }
27         });
28 
29         findViewById(R.id.btnStopSevice).setOnClickListener(new View.OnClickListener() {
30             @Override
31             public void onClick(View v) {
32                 
33                 //停止服务
34                 stopService(intent);
35             }
36         });
37     }
38 }

4,在MyService中进行相应的操作配置。

 1 package examples.ouc.com.learnsevice2;
 2 
 3 import android.app.Service;
 4 import android.content.Intent;
 5 import android.os.IBinder;
 6 
 7 public class MyService extends Service {
 8     public MyService() {
 9     }
10 
11     @Override
12     public IBinder onBind(Intent intent) {
13         // TODO: Return the communication channel to the service.
14         throw new UnsupportedOperationException("Not yet implemented");
15     }
16 
17     @Override
18     //重写的onStartCommand在startService()运行时自动运行。
19     public int onStartCommand(Intent intent, int flags, int startId) {
20         new Thread(){
21             @Override
22 
23             public void run() {
24                 super.run();
25 
26                 //通过设置输出一行代码来判断服务是否一直在运行中。
27                 while(true){
28                 System.out.println("sevice is running...");
29                 try {
30 
31                     //间隔2s输出一次
32                     sleep(2000);
33                 } catch (InterruptedException e) {
34                     e.printStackTrace();
35                 }}
36             }
37         }.start();
38         return super.onStartCommand(intent, flags, startId);
39     }
40 }

5,最后,我们就可以发布到我们的AVD上进行运行了,点击开始服务,就可以在AS下面run运行状态框中看到

  每隔两秒钟,就打印一行 sevice is running...

 

这个实例很简单,只是实现Service的后台运行,实际项目中,这个功能是十分重要的,希望自己日后用到时,能够想起来。。。菜鸟立flag

 

《二》service的绑定与声明周期

我们对上面的代码进行一些改动

1,首先,添加两个按钮,指示绑定服务,和解除绑定服务

技术分享
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:id="@+id/activity_main"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     android:paddingBottom="@dimen/activity_vertical_margin"
 8     android:paddingLeft="@dimen/activity_horizontal_margin"
 9     android:paddingRight="@dimen/activity_horizontal_margin"
10     android:paddingTop="@dimen/activity_vertical_margin"
11     android:orientation="vertical"
12     tools:context="examples.ouc.com.learnsevice2.MainActivity">
13 
14     <TextView
15         android:layout_width="wrap_content"
16         android:layout_height="wrap_content"
17         android:text="Hello World!" />
18 
19     <Button
20         android:text="Start Sevice"
21         android:layout_width="match_parent"
22         android:layout_height="wrap_content"
23         android:id="@+id/btnStartSevice" />
24 
25     <Button
26         android:text="Stop Sevice"
27         android:layout_width="match_parent"
28         android:layout_height="wrap_content"
29         android:id="@+id/btnStopSevice" />
30     <Button
31         android:text="Bind Sevice"
32         android:layout_width="match_parent"
33         android:layout_height="wrap_content"
34         android:id="@+id/btnBindSevice" />
35     <Button
36         android:text="Unbind Sevice"
37         android:layout_width="match_parent"
38         android:layout_height="wrap_content"
39         android:id="@+id/btnUnbindSevice" />
40 </LinearLayout>
View Code

2,然后我们在MainActivity中进行配置

技术分享
 1 package examples.ouc.com.learnsevice2;
 2 
 3 import android.content.ComponentName;
 4 import android.content.Context;
 5 import android.content.Intent;
 6 import android.content.ServiceConnection;
 7 import android.os.IBinder;
 8 import android.support.v7.app.AppCompatActivity;
 9 import android.os.Bundle;
10 import android.view.View;
11 
12 public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {
13 
14     private Intent intent;
15     @Override
16     protected void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         setContentView(R.layout.activity_main);
19 
20         //通过intent可以实现代码复用
21         intent =new Intent(MainActivity.this,MyService.class);
22 
23         //简单的对两个按钮设置监听器。
24         findViewById(R.id.btnStartSevice).setOnClickListener(this);
25 
26         findViewById(R.id.btnStopSevice).setOnClickListener(this);
27 
28         findViewById(R.id.btnBindSevice).setOnClickListener(this);
29         findViewById(R.id.btnUnbindSevice).setOnClickListener(this);
30     }
31 
32     @Override
33     public void onClick(View v) {
34         switch (v.getId()){
35             case R.id.btnStartSevice:
36                 startService(intent);
37                 break;
38             case R.id.btnStopSevice:
39                 stopService(intent);
40                 break;
41             case R.id.btnBindSevice:
42                 //bindService(Intent参数,服务的连接,服务的状态)
43                 bindService(intent,this,Context.BIND_AUTO_CREATE);
44                 break;
45             case R.id.btnUnbindSevice:
46                 unbindService(this);
47                 break;
48         }
49     }
50 
51     @Override
52     //服务被绑定成功后执行
53     public void onServiceConnected(ComponentName name, IBinder service) {
54         System.out.println("Service connected!");
55     }
56 
57     @Override
58     //服务所在进城崩溃或者北杀掉时候执行。
59     public void onServiceDisconnected(ComponentName name) {
60 
61     }
62 }
View Code

3,然后在MyService中进行一些改动,方便我们查看是否什么时候创建与销毁。

技术分享
 1 package examples.ouc.com.learnsevice2;
 2 
 3 import android.app.Service;
 4 import android.content.Intent;
 5 import android.os.Binder;
 6 import android.os.IBinder;
 7 
 8 public class MyService extends Service {
 9 
10     //通过设定一个flag,判断service是否仍然在运行
11     private boolean serviceRunning = false;
12     public MyService() {
13     }
14 
15     @Override
16     public IBinder onBind(Intent intent) {
17         // TODO: Return the communication channel to the service.
18         //throw new UnsupportedOperationException("Not yet implemented");
19         return new Binder();
20     }
21 
22     @Override
23     //重写的onStartCommand在startService()运行时自动运行。
24     public int onStartCommand(Intent intent, int flags, int startId) {
25         System.out.println("onStartCommand");
26         new Thread(){
27             @Override
28 
29             public void run() {
30                 super.run();
31 
32                 //通过设置输出一行代码来判断服务是否一直在运行中。
33                 //只有service仍在运行时,才会输出在这句话
34                 while(serviceRunning){
35                 System.out.println("sevice is running...");
36                 try {
37 
38                     //间隔2s输出一次
39                     sleep(2000);
40                 } catch (InterruptedException e) {
41                     e.printStackTrace();
42                 }}
43             }
44         }.start();
45         return super.onStartCommand(intent, flags, startId);
46     }
47 
48     @Override
49     public void onCreate() {
50         super.onCreate();
51         serviceRunning = true;
52         System.out.println("service create!");
53     }
54 
55     @Override
56     public void onDestroy() {
57         super.onDestroy();
58         System.out.println("service destory!");
59         serviceRunning = false;
60     }
61 }
View Code

4,然后我们可以发布,执行。

 

Android中Service的使用

标签:

原文地址:http://www.cnblogs.com/icyhusky/p/5982202.html

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