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

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

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

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

  这个就是我们的Service服务。

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

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

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

  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. </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>

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. }

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. }

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

Android中Service的使用的更多相关文章

  1. Android中Service(服务)详解

    http://blog.csdn.net/ryantang03/article/details/7770939 Android中Service(服务)详解 标签: serviceandroidappl ...

  2. Android中Service的使用详解和注意点(LocalService)

    Android中Service的使用详解和注意点(LocalService) 原文地址 开始,先稍稍讲一点android中Service的概念和用途吧~ Service分为本地服务(LocalServ ...

  3. Android中Service的一个Demo例子

    Android中Service的一个Demo例子  Service组件是Android系统重要的一部分,网上看了代码,很简单,但要想熟练使用还是需要Coding.  本文,主要贴代码,不对Servic ...

  4. Android中Service和Activity之间的通信

    启动Service并传递数据进去: Android中通过Intent来启动服务会传递一个Intent过去. 可以在Intent中通过putExtra()携带数据 Intent startIntent ...

  5. Android中Service 使用详解(LocalService + RemoteService)

    Service 简介: Service分为本地服务(LocalService)和远程服务(RemoteService): 1.本地服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外L ...

  6. Android中Service深入学习

    概述 1.当用户在与当前应用程序不同的应用程序时,Service可以继续在后台运行. 2.Service可以让其他组件绑定,以便和它交互并进行进程间通信. 3.Service默认运行在创建它的应用程序 ...

  7. (六)Android中Service通信

    一.启动Service并传递参数 传递参数时只需在startService启动的Intent中传入数据便可,接收参数时可在onStartCommand函数中通过读取第一个参数Intent的内容来实现 ...

  8. android中service启动后台程序

    Service是Android中一个类,它是Android四大组件之一,使用Service可以在后台执行长时间的操作( perform long-running operations in the b ...

  9. Android中Service与多个Activity通信

    由于项目需要,我们有时候需要在service中处理耗时操作,然后将结果发送给activity以更新状态.通常情况下,我们只需要在一个service与一个activity之间通信,通常这种情况下,我们使 ...

随机推荐

  1. MySQL中select * for update锁表的问题

    MySQL中select * for update锁表的问题 由于InnoDB预设是Row-Level Lock,所以只有「明确」的指定主键,MySQL才会执行Row lock (只锁住被选取的资料例 ...

  2. python : jquery实现左侧菜单

    左侧菜单 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3 ...

  3. Bellman-Ford

    看来一千个acmer有一千个迪杰斯特拉,Bellman-Ford也是一样. 看了刘汝佳的bellman-ford,简直和spfa一模一样啊!!! 松弛n -1 次还是可以松弛,说明有负环; 刘汝佳写得 ...

  4. sublime 自动编译

    Tools --> Build System --> New: { "shell_cmd": "cc.bat \"$file\"" ...

  5. Oracle的排序和限制条件(order by 和where)

    1.Order by 子句的使用 select column.... from .... order by ... 1) Order by子句在整个 select语句中的位置: 始终位于最后 2) o ...

  6. php多维数组去除空元素

    在php中去除数组中的空值可以使用array_filter() 这个函数 但是这个函数只能对一维数组起作用,一旦需要对多维数组去空就不行了,而且去除的空也包括(int)0,(string)0,使用起来 ...

  7. jQuery EasyUI教程之datagrid应用(一)

    最近一段时间都在做人事系统的项目,主要用到了EasyUI,数据库操作,然后抽点时间整理一下EasyUI的内容. 这里我们就以一个简洁的电话簿软件为基础,具体地说一下datagrid应用吧 datagr ...

  8. Install Google Pinyin on Ubuntu 14.04

    Install Google Pinyin on Ubuntu 14.04 I've been spending more and more time on Ubuntu and I'm not us ...

  9. memcache内存估算整理

    参考文章: http://blog.csdn.net/tonyxf121/article/details/7906428 http://zhihuzeye.com/archives/2361 memc ...

  10. java程序调用存储过程

    java程序调用存储过程       PL/SQL子程序,很多情况下是给应用程序来调用的,所有我们要掌握使用其他编程语言来调用我们写好的存储过程.下面我们介绍下使用java调用Oracle的存储过程. ...