zoukankan      html  css  js  c++  java
  • Android中Service的使用

    我个人的理解是:我们平时使用的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,然后我们可以发布,执行。

  • 相关阅读:
    4.计算机启动过程的简单介绍 计算机启动流程 计算机BIOS作用 POST 开机自检 计算机启动顺序 分区表 操作系统启动
    3.操作系统简单介绍 操作系统发展历史 批处理分时系统 操作系统是什么 操作系统对文件的抽象 进程 虚拟内存是什么 操作系统作用 操作系统功能
    2.计算机组成-数字逻辑电路 门电路与半加器 异或运算半加器 全加器组成 全加器结构 反馈电路 振荡器 存储 D T 触发器 循环移位 计数器 寄存器 传输门电路 译码器 晶体管 sram rom 微处理 计算机
    1.计算机发展阶段 计算机发展历史 机械式计算机 机电式计算机 电子计算机 逻辑电路与计算机 二极管 电子管 晶体管 硅 门电路 计算机 电磁学计算机二进制
    如何解决svn清理失败 不能更新 cleanup失败 cleanup乱码 更新乱码 svn更新提示清理 清理乱码不能清理 svn故障修复SVN cleanup 陷入死循环 svn cleanup时遇到错误怎么办
    eclipse svn插件卸载 重新安装 Subclipse卸载安装 The project was not built since its build path is incomplete This client is too old to work with the working copy at
    java for循环里面执行sql语句操作,有效结果只有一次,只执行了一次sql mybatis 循环执行update生效一次 实际只执行一次
    windows资源管理器多标签打开 windows文件夹多标签浏览 浏览器tab页面一样浏览文件夹 clover win8 win10 报错 无响应问题怎么解决 clover卡死 clover怎么换皮肤
    批处理启动vm虚拟机服务 vm12启动无界面启动vm虚拟机系统 windows上如何操作服务 sc net启动关闭服务
    不能ssh连接ubuntu linux 服务器 secureCRT不能ssh连接服务器 不能远程ssh连接虚拟机的ubuntu linux
  • 原文地址:https://www.cnblogs.com/icyhusky/p/5982202.html
Copyright © 2011-2022 走看看