我个人的理解是:我们平时使用的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中配置这两个按钮。

 package examples.ouc.com.learnsevice2;

 import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View; public class MainActivity extends AppCompatActivity { private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //通过intent可以实现代码复用
intent =new Intent(MainActivity.this,MyService.class); //简单的对两个按钮设置监听器。
findViewById(R.id.btnStartSevice).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { //开始服务
startService(intent);
}
}); findViewById(R.id.btnStopSevice).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { //停止服务
stopService(intent);
}
});
}
}

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

 package examples.ouc.com.learnsevice2;

 import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MyService extends Service {
public MyService() {
} @Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
} @Override
//重写的onStartCommand在startService()运行时自动运行。
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(){
@Override public void run() {
super.run(); //通过设置输出一行代码来判断服务是否一直在运行中。
while(true){
System.out.println("sevice is running...");
try { //间隔2s输出一次
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}}
}
}.start();
return super.onStartCommand(intent, flags, startId);
}
}

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

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

 

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

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

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

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

 <?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" />
<Button
android:text="Bind Sevice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnBindSevice" />
<Button
android:text="Unbind Sevice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnUnbindSevice" />
</LinearLayout>

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

 package examples.ouc.com.learnsevice2;

 import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View; public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection { private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //通过intent可以实现代码复用
intent =new Intent(MainActivity.this,MyService.class); //简单的对两个按钮设置监听器。
findViewById(R.id.btnStartSevice).setOnClickListener(this); findViewById(R.id.btnStopSevice).setOnClickListener(this); findViewById(R.id.btnBindSevice).setOnClickListener(this);
findViewById(R.id.btnUnbindSevice).setOnClickListener(this);
} @Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnStartSevice:
startService(intent);
break;
case R.id.btnStopSevice:
stopService(intent);
break;
case R.id.btnBindSevice:
//bindService(Intent参数,服务的连接,服务的状态)
bindService(intent,this,Context.BIND_AUTO_CREATE);
break;
case R.id.btnUnbindSevice:
unbindService(this);
break;
}
} @Override
//服务被绑定成功后执行
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("Service connected!");
} @Override
//服务所在进城崩溃或者北杀掉时候执行。
public void onServiceDisconnected(ComponentName name) { }
}

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

 package examples.ouc.com.learnsevice2;

 import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; public class MyService extends Service { //通过设定一个flag,判断service是否仍然在运行
private boolean serviceRunning = false;
public MyService() {
} @Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Not yet implemented");
return new Binder();
} @Override
//重写的onStartCommand在startService()运行时自动运行。
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onStartCommand");
new Thread(){
@Override public void run() {
super.run(); //通过设置输出一行代码来判断服务是否一直在运行中。
//只有service仍在运行时,才会输出在这句话
while(serviceRunning){
System.out.println("sevice is running...");
try { //间隔2s输出一次
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}}
}
}.start();
return super.onStartCommand(intent, flags, startId);
} @Override
public void onCreate() {
super.onCreate();
serviceRunning = true;
System.out.println("service create!");
} @Override
public void onDestroy() {
super.onDestroy();
System.out.println("service destory!");
serviceRunning = false;
}
}

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. [Scrapy] Mac安装Scrapy

    Mac安装Scrapy Mac版本 10.11 El Captain. 前一段想在Mac上用Scrapy,各种问题.有一个不错的工具:Anaconda. 安装Anaconda 下载地址 我还是下pyt ...

  2. centos7 nginx配置httpsCenos(6.6/7.1)下从源码安装Python+Django+uwsgi+nginx环境部署(二)

     1.yum安装nginx 下载对应当前系统版本的nginx包(package) # wget  http://nginx.org/packages/centos/7/noarch/RPMS/ngin ...

  3. [问题2014A03] 复旦高等代数 I(14级)每周一题(第五教学周)

    [问题2014A03]  设 \(A=(a_{ij})\) 为 \(n\,(n\geq 3)\) 阶方阵,\(A_{ij}\) 为第 \((i,j)\) 元素 \(a_{ij}\) 在 \(|A|\) ...

  4. C#中调用Matlab人工神经网络算法实现手写数字识别

    手写数字识别实现 设计技术参数:通过由数字构成的图像,自动实现几个不同数字的识别,设计识别方法,有较高的识别率 关键字:二值化  投影  矩阵  目标定位  Matlab 手写数字图像识别简介: 手写 ...

  5. LTE Module User Documentation(翻译9)——Using the EPC with emulation mode

    LTE用户文档 (如有不当的地方,欢迎指正!) 15 Using the EPC with emulation mode(使用仿真方式的 EPC)     在上一节中,我们使用点对点链路连接基站和服务 ...

  6. 用Python编写的第一个回测程序

    用Python编写的第一个回测程序 2016-08-06 def savfig(figureObj, fn_prefix1='backtest8', fn_prefix2='_1_'): import ...

  7. Retrofit 2.0使用(2)如何使用@Body的形式发送Post

    在使用Retrofit的时候如果只是有几个参数我们可以用@Querry的形式,然后需要使用','隔开 但是在需要@Querry的参数多了之后,如果再用上面的方式就会造成参数写了一大堆的麻烦事 所以Re ...

  8. linux如何修改文件或目录的权限(chmod)

    chmod命令是linux上用于改变权限的命令,-R 是递归遍历子目录,因为你要操作的文件使用的*通配符.777,第一个7代表文件所属者的权限,第二个7代表文件所属者所在组的权限,第三个7代表其它用户 ...

  9. iOS开发技巧

    一.寻找最近公共View 我们将一个路径中的所有点先放进 NSSet 中.因为 NSSet 的内部实现是一个 hash 表,所以查找元素的时间复杂度变成了 O(1),我们一共有 N 个节点,所以总时间 ...

  10. Spring 事务管理 01 ——

    目录: 参考: 1.Spring 事务管理高级应用难点剖析: 第 1 部分