Android 启动后台运行程序(Service)
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)
- package com.android.myservice;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class ServiceDemo extends Activity implements OnClickListener {
- private static final String TAG = "ServiceDemo";
- Button buttonStart, buttonStop;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- buttonStart = (Button) findViewById(R.id.buttonStart);
- buttonStop = (Button) findViewById(R.id.buttonStop);
- buttonStart.setOnClickListener(this);
- buttonStop.setOnClickListener(this);
- }
- public void onClick(View src) {
- switch (src.getId()) {
- case R.id.buttonStart:
- Log.i(TAG, "onClick: starting service");
- startService(new Intent(this, MyService.class));
- break;
- case R.id.buttonStop:
- Log.i(TAG, "onClick: stopping service");
- stopService(new Intent(this, MyService.class));
- break;
- }
- }
- }
除此之外还要在Manifest里面声明服务:(AndroidManifest.xml)
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.myservice">
- <application android:label="@string/app_name">
- <activity android:name=".ServiceDemo" android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN"/>
- <category android:name="android.intent.category.LAUNCHER"/>
- </intent-filter>
- </activity>
- <service android:enabled="true" android:name=".MyService"/>
- </application>
- </manifest>
定义Service(MyService.java)
- package com.android.myservice;
- import android.app.Service;
- import android.content.Intent;
- import android.media.MediaPlayer;
- import android.os.IBinder;
- import android.util.Log;
- import android.widget.Toast;
- public class MyService extends Service {
- private static final String TAG = "MyService";
- MediaPlayer player;
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- @Override
- public void onCreate() {
- Toast.makeText(this, "My Service created", Toast.LENGTH_LONG).show();
- Log.i(TAG, "onCreate");
- player = MediaPlayer.create(this, R.raw.braincandy);
- player.setLooping(false);
- }
- @Override
- public void onDestroy() {
- Toast.makeText(this, "My Service Stoped", Toast.LENGTH_LONG).show();
- Log.i(TAG, "onDestroy");
- player.stop();
- }
- @Override
- public void onStart(Intent intent, int startid) {
- Toast.makeText(this, "My Service Start", Toast.LENGTH_LONG).show();
- Log.i(TAG, "onStart");
- player.start();
- }
- }
layout文件夹中是main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:gravity="center">
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" android:text="@string/services_demo" android:gravity="center" android:textSize="20sp" android:padding="20dp"/>
- <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonStart" android:text="@string/start"></Button>
- <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/stop" android:id="@+id/buttonStop"></Button>
- </LinearLayout>
values 文件夹中是strings.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="start">Start</string>
- <string name="stop">Stop</string>
- <string name="services_demo">Service Demo</string>
- </resources>

Android 启动后台运行程序(Service)的更多相关文章
- nohup命令(Linux终端启动后台运行程序)
1. nohup指令基本概念: nohup: 不挂断的运行,并没有后台运行功能,用nohup运行命令可以使命令永久执行下去,和用户终端没有关系,断开SSH不影响运行,&是后台运行. nohup ...
- 5、清理mac缓存和关闭后台运行程序
一.清理mac 缓存 1.用鼠标点击桌面,然后按快捷键Command+Shift+G前往文件夹 2.输入路径:~/Library/Caches/ 3.清除所有的数据,把所有的Caches文件夹得都行 ...
- Linux后台运行程序
Linux后台运行程序 最近写的程序需要部署到Linux服务器上,按照以前的方式,在运行后面增加&,程序会切换为后台运行.但因为Linux一般是通过ssh远程登录的,等到退出当前session ...
- tmux 后台运行程序
之前写过tmux分屏,其实这个只是方便写代码啥的,那都还不是最重要的.跑模型时,一般一跑就是一整天都是常事. 电脑关机,睡眠,ssh连接失效都会断了程序运行. solution:tmux后台运行程序! ...
- Linux下使用nohup实现在后台运行程序(转)
相比上一篇http://www.cnblogs.com/EasonJim/p/6833417.html使用screen实现后台运行程序,各有各的好处,多一种选择吧. Linux下一般比如想让某个程序在 ...
- 用Cygwin实现在window环境下使用Linux命令-nohup 来后台运行程序
1.安装Cygwin 下载 cygdrive-选择64或32位 http://www.cygwin.com/ 注:可以百度搜索安装步骤 2.配置它的环境变量 添加到path路径中 3.cmd 执 ...
- 后台运行程序nohup的使用
linux后台运行程序 nohup python3 test.py >output 2>&1 & 参数解释 用途:不挂断地运行命令. 语法:nohup Command [ ...
- linux中启动 java -jar 后台运行程序
直接用java -jar xxx.jar,当退出或关闭shell时,程序就会停止掉.以下方法可让jar运行后一直在后台运行. 1. java -jar xxx.jar & 说明: 在末尾加入 ...
- linux 后台运行程序
有些时候,我们需要在终端启动一个程序,并使之运行--但是如果关闭终端,那么这个程序也就随着关闭了.那么有没有什么方法在关闭终端后,让已经从这个终端启动的程序继续运行呢? 前置知识: xterm,con ...
随机推荐
- 〖Linux〗apt-get wait for another apt process
#!/bin/bash i= tput sc >& || \ >&; do )) in ) j="-" ;; ) j="\\" ;; ...
- python之函数用法divmod
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法divmod #http://python.jobbole.com/81480/ #d ...
- CAS 5.1.x 的搭建和使用(二)—— 通过Overlay搭建服务端-其它配置说明
CAS单点登录系列: CAS 5.1.x 的搭建和使用(一)—— 通过Overlay搭建服务端 CAS5.1.x 的搭建和使用(二)—— 通过Overlay搭建服务端-其它配置说明 CAS5.1.x ...
- 如何让bat,cmd文件后台运行?如何把文件打包成EXE?
方法1:在“运行”中输入IEXPRESS 这是WINDOWS自带的打包程序,好像也可以生成安装包. 下一步-下一步-随便填个名字(下一步)-下一步-下一步-ADD(选好你的BAT文件 继 ...
- JDBC实战案例--利用jdbc实现的宠物信息管理系统
一.需求: 利用jdbc实现对宠物的信息进行管理的一套系统 宠物信息:宠物ID,宠物类别,宠物名字,宠物性别,宠物年龄,宠物入库日期 系统完成功能:实现对宠物信息的录入,修改,删除,查询. 二.解决方 ...
- history设置时间戳
Linux查看历史命令,很关键!history,默认没有时间戳... 01.设置系统环境变量 echo 'export HISTTIMEFORMAT="%F %T `whoami` &qu ...
- mysql优化不可不做的事情
写在前面的话:总是在灾难发生后,才想起容灾的重要性:总是在吃过亏后,才记得有人提醒过 设计原则 1.不在数据库做运算:cpu计算务必移至业务层 2.控制单表数据量:单表记录控制在1000w 3.控制列 ...
- HDUOJ----Ignatius and the Princess III
Ignatius and the Princess III Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K ...
- yaml语法三大规则
规则一:缩进 yaml使用一个固定的缩进风格表示数据层结构关系,Saltstack需要每个缩进级别由两个空格组成.一定不能使用tab键 规则二:冒号 yaml: mykey: my_value 每 ...
- Remote 'attachhome' failed on nodes:XXX
RAC安装过程中,在安装GI的时候报如下错误: 解决方法: 根据提示执行以下脚本 $ /u01/app//grid/oui/bin/runInstaller -attachHome -noCluste ...