ServiceAndroid中一个类,它是Android四大组件之一,使用Service可以在后台执行长时间的操作( perform long-running operations in the background ),Service并不与用户产生UI交互。其他的应用组件可以启动Service,即便用户切换了其他应用,启动的Service仍可在后台运行。一个组件可以与Service绑定并与之交互,甚至是跨进程通信(IPC)。例如,一个Service可以在后台执行网络请求、播放音乐、执行文件读写操作或者与 content provider交互 等。

ps:附上一个service组件介绍的网站:https://blog.csdn.net/scott2017/article/details/51505801

下面是一个音乐后台播放的例子:

1.Activity类

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button; /**
* Created by cj on 2018/3/28.
*/ public class ServiceDemo extends Activity implements View.OnClickListener{ private static final String TAG = "ServiceDemo";
Button buttonStart, buttonStop; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.servicedemo); 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;
}
} }
2.Service子类:
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Debug;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast; /**
* Created by cj on 2018/3/28.
*/ public class MyService extends Service { private static final String TAG = "MyService";
private final static int GRAY_SERVICE_ID = 1001;
MediaPlayer player; @Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public void onCreate() {
Toast.makeText(this,"MyService Created",Toast.LENGTH_SHORT).show();
Log.i(TAG,"oncreated");
player = MediaPlayer.create(this,R.raw.huanghun); //此处的R.raw.huanghun为要播放的音乐资源。在res文件夹下创建raw目录,huanghun.mp3为音乐资源,放到创建好的raw文件夹下
player.setLooping(false);
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
//sdk小于18时启动一个状态栏通知
if(Build.VERSION.SDK_INT<18){
startForeground(GRAY_SERVICE_ID,new Notification());
}else{
//sdk大于18 时启动一个状态栏通知
Intent intent1 = new Intent(this,GrayInnerService.class);
startService(intent1);
startForeground(GRAY_SERVICE_ID,new Notification());
}
return super.onStartCommand(intent, flags, startId);
} //给API >= 18 的平台上做灰色保护手段
public class GrayInnerService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(GRAY_SERVICE_ID, new Notification());
stopForeground(true);
stopSelf(); return super.onStartCommand(intent, flags, startId);
}
} @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();
}
}
3.布局文件
<?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/servicesdemo" 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>
4.String.xml文件
<resources>
<string name="app_name">update</string> //此处为运用程序的名称,一般项目创建时自带
<string name="start">播放</string>
<string name="stop">停止</string>
<string name="servicesdemo">Service Demo</string>
</resources>
5.manifest.xml文件中配置

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".ServiceDemo">
<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"/> //此处配置,name为service的子类。
</application>


android中service启动后台程序的更多相关文章

  1. 用JQuery中的Ajax方法获取web service等后台程序中的方法

    用JQuery中的Ajax方法获取web service等后台程序中的方法 1.准备需要被前台html页面调用的web Service,这里我们就用ws来代替了,代码如下: using System; ...

  2. Android中Service(服务)详解

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

  3. Android中Service深入学习

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

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

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

  5. init.rc文件中面启动c++程序,通过jni调用java实现

    </pre><p>注:假设是自己的myself.jar包,还要修改例如以下:</p><p>target/product/core_base.mk PRO ...

  6. Android中Service的一个Demo例子

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

  7. android中退出当前应用程序的四种方法

    android中退出当前应用程序的四种方法 [IT168 技术]Android程序有很多Activity,比如说主窗口A,调用了子窗口B,如果在B中直接finish(), 接下里显示的是A.在B中如何 ...

  8. Linux和Windows启动后台程序

    平时很多时候,我们需要通过脚本命令调用执行程序,集成一体后方便使用快捷.但是启动脚本窗口比较碍眼,能设置为后台运行既方便又美观. Linux启动后台程序 1.后台执行 nohup方法:不挂断的运行命令 ...

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

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

随机推荐

  1. Daily scrum 2015.10.19

    这周是我们团队项目开始的第一周.我们的团队项目是“北航社团平台”,一个致力于打造北航社团资讯整合.社团工作服务与社团商品销售的一站式网络平台. 一.会议内容 1. 总体分工,江昊同学担任项目PM,王若 ...

  2. 2017-2018-2 『Java程序设计』课程 结对编程练习_四则运算

    相关测试过程截图(JUnit) JudgeTest:对计算及将整数化为分数的测试 SuffixExpressionTest:中缀转后缀的测试 RationalNumberTest:对RationalN ...

  3. java的小学生四则运算

    import java.awt.*; import java.awt.event.*; import java.io.FileNotFoundException; import java.io.IOE ...

  4. srTCM和trTCM介绍

    本文是用于QoS Meter功能的算法的RFC的阅读笔记.DPDK的QoS_meter示例程序用的就是这个算法. srTCM srTCM的英文全称是Single Rate Three Color Ma ...

  5. Express搭建NodeJS项目

    1.安装Node.js: 2.安装npm; 3.安装Express; 在本例中默认全局安装express 安装express生成器 如果没有安装express-generator或安装路径不对,会报以 ...

  6. 关于VS2005中C#代码用F12转到定义时,总是显示从元数据的问题

    元数据是:NET 程序集中的标记信息. 是在代码中选择了转到定义时候给定位的吧.因为没有找到源代码,VS通过反射读取元数据中的信息生成了那个. 解决方法: 1. 要把项目先添加到解决方案中. 2. 再 ...

  7. APP端测试与web端测试的区别

    想要知道APP端测试与web端测试的区别 ,那么我们就要先来了解,web和app的区别. web项目,一般都是b/s架构,基于浏览器的,而app则是c/s的,必须要有客户端.那么在系统测试测试的时候就 ...

  8. css中定位功能的特性

    它有四大特性,页面找不到盒子的情况 1.z-index值表示谁压着谁,数值大的压盖数值小的 2.只有定位了的元素,才有z-index.也就是说,不管相对定位,绝对定位,固定定位,都可以使用z-inde ...

  9. validate效验规则

    ] } }, messages:{ name:{ required:"最少为2个字!" }, tel:{ required:"请填写手机号码!", isMobi ...

  10. UVA11248_Frequency Hopping

    给一个有向网络,求其1,n两点的最大流量是否不小于C,如果小于,是否可以通过修改一条边的容量使得最大流量不小于C? 首先对于给定的网络,我们可以先跑一遍最大流,然后先看流量是否大于C. 然后保存跑完第 ...