Android开发中,当需要创建在后台运行的程序的时候,就要使用到Service。Service 可以分为有无限生命和有限生命两种。特别需要注意的是Service跟Activities是不同的(简单来说可以理解为后台与前台的区别),例如,如果需要使用Service的话,需要调用startService(),从而利用startService()去调用Service中的OnCreate()和onStart()方法来启动一个后台的Service。
      启动一个Service的过程如下:context.startService()  ->onCreate()- >onStart()->Service running其中onCreate()可以进行一些服务的初始化工作,onStart()则启动服务。
      停止一个Service的过程如下:context.stopService() | ->onDestroy() ->Service stop
      接下来的实例是一个利用后台服务播放音乐的小例子,点击start运行服务,点击stop停止服务。
ServicesDemo.java(是一个Activity)

  1. package com.android.myservice;
  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.util.Log;
  6. import android.view.View;
  7. import android.view.View.OnClickListener;
  8. import android.widget.Button;
  9. public class ServiceDemo extends Activity implements OnClickListener {
  10. private static final String TAG = "ServiceDemo";
  11. Button buttonStart, buttonStop;
  12. @Override
  13. public void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.main);
  16. buttonStart = (Button) findViewById(R.id.buttonStart);
  17. buttonStop = (Button) findViewById(R.id.buttonStop);
  18. buttonStart.setOnClickListener(this);
  19. buttonStop.setOnClickListener(this);
  20. }
  21. public void onClick(View src) {
  22. switch (src.getId()) {
  23. case R.id.buttonStart:
  24. Log.i(TAG, "onClick: starting service");
  25. startService(new Intent(this, MyService.class));
  26. break;
  27. case R.id.buttonStop:
  28. Log.i(TAG, "onClick: stopping service");
  29. stopService(new Intent(this, MyService.class));
  30. break;
  31. }
  32. }
  33. }

除此之外还要在Manifest里面声明服务:(AndroidManifest.xml)

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.android.myservice">
  4. <application android:label="@string/app_name">
  5. <activity android:name=".ServiceDemo" android:label="@string/app_name">
  6. <intent-filter>
  7. <action android:name="android.intent.action.MAIN"/>
  8. <category android:name="android.intent.category.LAUNCHER"/>
  9. </intent-filter>
  10. </activity>
  11. <service android:enabled="true" android:name=".MyService"/>
  12. </application>
  13. </manifest>

定义Service(MyService.java)

  1. package com.android.myservice;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.media.MediaPlayer;
  5. import android.os.IBinder;
  6. import android.util.Log;
  7. import android.widget.Toast;
  8. public class MyService extends Service {
  9. private static final String TAG = "MyService";
  10. MediaPlayer player;
  11. @Override
  12. public IBinder onBind(Intent intent) {
  13. return null;
  14. }
  15. @Override
  16. public void onCreate() {
  17. Toast.makeText(this, "My Service created", Toast.LENGTH_LONG).show();
  18. Log.i(TAG, "onCreate");
  19. player = MediaPlayer.create(this, R.raw.braincandy);
  20. player.setLooping(false);
  21. }
  22. @Override
  23. public void onDestroy() {
  24. Toast.makeText(this, "My Service Stoped", Toast.LENGTH_LONG).show();
  25. Log.i(TAG, "onDestroy");
  26. player.stop();
  27. }
  28. @Override
  29. public void onStart(Intent intent, int startid) {
  30. Toast.makeText(this, "My Service Start", Toast.LENGTH_LONG).show();
  31. Log.i(TAG, "onStart");
  32. player.start();
  33. }
  34. }

layout文件夹中是main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:gravity="center">
  7. <TextView
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content" android:text="@string/services_demo" android:gravity="center" android:textSize="20sp" android:padding="20dp"/>
  10. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonStart" android:text="@string/start"></Button>
  11. <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/stop" android:id="@+id/buttonStop"></Button>
  12. </LinearLayout>

values 文件夹中是strings.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string name="start">Start</string>
  4. <string name="stop">Stop</string>
  5. <string name="services_demo">Service Demo</string>
  6. </resources>

Android 启动后台运行程序(Service)的更多相关文章

  1. nohup命令(Linux终端启动后台运行程序)

    1. nohup指令基本概念: nohup: 不挂断的运行,并没有后台运行功能,用nohup运行命令可以使命令永久执行下去,和用户终端没有关系,断开SSH不影响运行,&是后台运行. nohup ...

  2. 5、清理mac缓存和关闭后台运行程序

    一.清理mac 缓存  1.用鼠标点击桌面,然后按快捷键Command+Shift+G前往文件夹 2.输入路径:~/Library/Caches/ 3.清除所有的数据,把所有的Caches文件夹得都行 ...

  3. Linux后台运行程序

    Linux后台运行程序 最近写的程序需要部署到Linux服务器上,按照以前的方式,在运行后面增加&,程序会切换为后台运行.但因为Linux一般是通过ssh远程登录的,等到退出当前session ...

  4. tmux 后台运行程序

    之前写过tmux分屏,其实这个只是方便写代码啥的,那都还不是最重要的.跑模型时,一般一跑就是一整天都是常事. 电脑关机,睡眠,ssh连接失效都会断了程序运行. solution:tmux后台运行程序! ...

  5. Linux下使用nohup实现在后台运行程序(转)

    相比上一篇http://www.cnblogs.com/EasonJim/p/6833417.html使用screen实现后台运行程序,各有各的好处,多一种选择吧. Linux下一般比如想让某个程序在 ...

  6. 用Cygwin实现在window环境下使用Linux命令-nohup 来后台运行程序

    1.安装Cygwin 下载 cygdrive-选择64或32位   http://www.cygwin.com/ 注:可以百度搜索安装步骤 2.配置它的环境变量 添加到path路径中 3.cmd  执 ...

  7. 后台运行程序nohup的使用

    linux后台运行程序 nohup python3 test.py >output 2>&1 & 参数解释 用途:不挂断地运行命令. 语法:nohup Command [ ...

  8. linux中启动 java -jar 后台运行程序

    直接用java -jar xxx.jar,当退出或关闭shell时,程序就会停止掉.以下方法可让jar运行后一直在后台运行. 1. java -jar xxx.jar & 说明: 在末尾加入 ...

  9. linux 后台运行程序

    有些时候,我们需要在终端启动一个程序,并使之运行--但是如果关闭终端,那么这个程序也就随着关闭了.那么有没有什么方法在关闭终端后,让已经从这个终端启动的程序继续运行呢? 前置知识: xterm,con ...

随机推荐

  1. eclipse 导入tortoiseSVN检出项目,不显示svn信息(eclipse安装svn插件)

      eclipse 导入tortoiseSVN检出项目,不显示svn信息(eclipse安装svn插件) CreateTime--2018年5月10日14:10:35 Author:Marydon 1 ...

  2. xml DTD中的ELEMENT和ATTLIST

    是W3C的一个文档类型定义规则文件,是用来让浏览器根据你定义的DTD(文档类型定义)来解释页面代码的. doctype声明指出阅读程序应该用什么规则集来解释文档中的标记.在Web文档的情况下,“阅读程 ...

  3. 不止是动态化:Weex项目和阿里无线技术开源方向

    这是开发者正在书写的峥嵘岁月.受益开源,回馈社区.阿里巴巴集团已经开源115个项目,并正式加入FSF基金会,Apache基金会,linux 基金会和Xen的顾问团队,并在云栖大会北京峰会宣布AliSQ ...

  4. 解决sitemesh3装饰页面不能使用freemarker标签问题

    如题,这个问题其实在sitemesh2中已经很好的解决了,不过在sitemesh3中可能没有解决,所以要自己写代码解决了,下面我先讲下sitemesh2是如何解决的: <servlet> ...

  5. ASP.NET#在设计窗口上添加了一个SqlDataSource控件后,没有显示出来?

    在设计窗口上添加了一个SqlDataSource控件后,没有显示出来,但后台代码是有的 处理的办法:菜单栏->视图->可视辅助->ASP.NET非可视控件 (我用的是VS2012)

  6. ArchLinux新版本(pacstrap安装)及国内较优源推荐

    下载安装镜像和配置虚拟机都略过. 进入安装模式以后第一件事是要进行分区,分区很重要,怎么分区是由后面的grub的模式来决定的.grub有3种模式,分别对应grub-bios-gpt,grub-bios ...

  7. 由select/epoll返回的非阻塞connect还会是EINPROGRESS状态吗?

    一般情况下,我们像下面代码中所示的这样使用非阻塞connect: #include <stdio.h> #include <stdlib.h> #include <str ...

  8. HDUOJ----4504 威威猫系列故事——篮球梦

    威威猫系列故事——篮球梦 Time Limit: 300/100 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)Total ...

  9. 微软解决方案框架 - MSF的团队模型、MSF的开发模型,关于SA系统分析师信息的一篇好帖子

    msf中的开发模型 书中关于六个小组的人员的案例: MSF 组队模型 v. 3.1-http://bbs.51cto.com/thread-1171-1.html 微软解决方案框架 - MSF的团队模 ...

  10. [译]流言终结者 —— SQL Server 是Sybase的产品而不是微软的

    http://www.cnblogs.com/xxxtech/archive/2011/12/30/2307859.html by Euan Garden 这些年来我听说过关于这个流言的许多版本,其中 ...