效果图:

layout的main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <Button
android:id="@+id/start"
android:onClick="onClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="startService" /> <Button
android:id="@+id/stop"
android:onClick="onClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stopService" /> <Button
android:id="@+id/bind"
android:onClick="onClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="绑定(bindService(Intent intent2))" /> <Button
android:id="@+id/unbind"
android:onClick="onClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="解除绑定(unbindService(Intent intent2))" />
<Button
android:id="@+id/music"
android:onClick="onClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="music" />
<Button
android:id="@+id/stopmusic"
android:onClick="onClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stopmusic" />
</LinearLayout>

  

MainActivity:

package com.wyl.servicedemo;

import com.wyl.servicedemo.MyBindService.MyBinder;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast; public class MainActivity extends Activity {
Intent intent ;
Intent intent2;
MyBindService service;//定义一个类型为继承了Service类的MyBindService类的成员变量,
/*
* 使用bindService(intent2, conn, Service.BIND_AUTO_CREATE);方式开启一个
* Service服务必须实例化一个ServiceConnection用来接收extends Service的MyBindService里
* 回传的数据
*/
ServiceConnection conn = new ServiceConnection() {
/**
* 当启动源跟Service的连接意外丢失的时候会调用这个方法
* 比如当Service崩溃了或者被强行kill了。
*/
@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
int s = service.SIZE;
// Toast.makeText(this, "onServiceConnected()方法所在线程为:"+Thread.currentThread().getName(), 100).show();
System.out.println("SIZE:"+s+",onServiceDisconnected()方法所在线程为:"+Thread.currentThread().getName());
} @Override
public void onServiceConnected(ComponentName arg0, IBinder binder) {
//接收会传来的数据,根据这个service我们可以获取一些数据
service = ((MyBinder)binder).getService();
int s = service.SIZE;
// Toast.makeText(this, "onServiceConnected()方法所在线程为:"+Thread.currentThread().getName(), 100).show();
System.out.println("SIZE:"+s+",onServiceConnected()方法所在线程为:"+Thread.currentThread().getName());
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); } public void onClick(View view) {
switch (view.getId()) {
case R.id.start:
intent = new Intent(MainActivity.this,MyService.class);
System.out.println("onClick.startService()");
Toast.makeText(this, "开启线程startService", 500).show();
startService(intent);
break;
case R.id.stop:
System.out.println("onClick.stopService()");
Toast.makeText(this, "关闭线程stopService", 500).show();
stopService(intent);
break; case R.id.bind://绑定
intent2 = new Intent(MainActivity.this,MyBindService.class);
//第三个参数是自动开启服务的作用,第二个参数不能够为空,且为ServiceConnection conn类型,
bindService(intent2, conn, Service.BIND_AUTO_CREATE);
System.out.println("onClick.bindService()");
Toast.makeText(this, "开启绑定", 500).show();
break; case R.id.unbind://解除绑定
stopService(intent2);
unbindService(conn);//解除绑定,这个参数一个不能够为空,unbindService(ServiceConnection conn);
System.out.println("onClick.unbindService()");
Toast.makeText(this, "解除绑定", 500).show();
break; case R.id.music://播放音乐
service.Play();
Toast.makeText(this, "播放音乐", 500).show();
break;
case R.id.stopmusic://暂停音乐
service.Play();
Toast.makeText(this, "暂停音乐", 500).show();
break;
}
}
}

  MyService.java (这个service只是用来普通的stopService(),和startService()):

package com.wyl.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MyService extends Service{ @Override
/*
* Parameters
intent The Intent that was used to bind to this service,
as given to Context.bindService. Note that any extras
that were included with the Intent at that point will
not be seen here.
Returns
Return an IBinder through which clients can call on to the service.
*/
public void onCreate() {
System.out.println("BindService.onCreate()");
super.onCreate();
}; public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
System.out.println("BindService.onBind");
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
System.out.println("onStartCommand()方法。。。。");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("myServie.ondestroy()....");
super.onDestroy();
}
}

  MyBindService.java :用bind的方式来绑定service,

package com.wyl.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder; public class MyBindService extends Service{
public static int SIZE = 3;
@Override
public void onCreate() {
System.out.println("onCreate()方法。。。");
super.onCreate();
}
/**
* bind方式开启service,必须写一个类继承Binder,
* 然后再IBinder onBind(Intent arg0)方法中返回所需要返回的值
* @author wyl
*
*/
public class MyBinder extends Binder{
public MyBindService getService(){
System.out.println("MyBinder extends Binder的MyBindService getService()方法。。。");
return MyBindService.this;
}
} @Override
public IBinder onBind(Intent arg0) {
System.out.println("public IBinder onBind(Intent arg0) 方法。。。");
/*
* onBind(Intent arg0),想回传数据,
* 必须写上面的public class MyBinder extends Binder
*/
return new MyBinder();
}
@Override
public boolean onUnbind(Intent intent) {
System.out.println("onUnbind(Intent intent)方法。。。");
return super.onUnbind(intent);
} @Override
public void unbindService(ServiceConnection conn) {
System.out.println("unbindService(ServiceConnection conn)方法。。。");
super.unbindService(conn);
} @Override
public void onDestroy() {
System.out.println("onDestroy()方法。。。");
super.onDestroy();
} public void Play(){
System.out.println("MyBindService.Play()方法,播放音乐");
}
public void Pause(){
System.out.println("MyBindService.Pause()方法,暂停");
} }

  有一点要说明:写service或者自己定义了一个新的activity等,这些都需要在清单文件里进行注册。

否则不能够生效,有的时候程序还不报错,页面上还只是空白,所以不好找原因。要牢记一定在在清单文件里注册。

Android:ServiceDemo的更多相关文章

  1. Android四大组件之—— 使用服务进行后台操作

    什么是服务 服务是一个没有可视化界面的组件,它可以在后台长期运行并进行各种操作. 服务的创建 我们只需要继承Service类并实现相应的方法即可创建服务 要想启动服务,还得在AndroidManife ...

  2. Android入门(十八)服务

    原文链接:http://www.orlion.ga/674/ 一.定义一个服务 创建一个项目ServiceDemo,然后在这个项目中新增一个名为 MyService的类,并让它继承自 Service, ...

  3. 一个帖子学会Android开发四大组件

    来自:http://www.cnblogs.com/pepcod/archive/2013/02/11/2937403.html 这个文章主要是讲Android开发的四大组件,本文主要分为 一.Act ...

  4. Android 保持Service不被Kill掉的方法--双Service守护 && Android实现双进程守护

    本文分为两个部分,第一部分为双Service守护,第二部分为双进程守护 第一部分: 一.Service简介:Java.lang.Object ↳Android.content.Context  ↳an ...

  5. Android Service学习之本地服务

    Service是在一段不定的时间运行在后台,不和用户交互应用组件.每个Service必须在manifest中 通过来声明.可以通过contect.startservice和contect.bindse ...

  6. Android开发之Service的写法以及与Activity的通信

    Service的总结: 1.按运行地点分类: 类别 区别  优点 缺点   应用 本地服务(Local) 该服务依附在主进程上,  服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外 ...

  7. 保持Service不被Kill掉的方法--双Service守护 && Android实现双进程守护

    本文分为两个部分,第一部分为双Service守护,第二部分为双进程守护 第一部分: 一.Service简介:Java.lang.Object ↳Android.content.Context  ↳an ...

  8. Android Service生命周期及用法

    Service概念及用途:Android中的服务,它与Activity不同,它是不能与用户交互的,不能自己启动的,运行在后台的程序,如果我们退出应用时,Service进程并没有结束,它仍然在后台运行, ...

  9. Android 之Service

    service是运行在后台的服务,你可以启动一个服务Service来播放音乐,或者记录你地理信息位置的改变,或者启动一个服务来运行并一直监听某种动作. 接下来分析一下service 的生命周期: 1: ...

随机推荐

  1. css伪类伪元素

    在CSS中,模式(pattern)匹配规则决定哪种样式规则应用于文档树(document tree)的哪个元素.这些模式叫着选择符(selector). 一条CSS规则(rule)是选择符{属性:值; ...

  2. C#指定目录存放DLL

    C#开发中,常常会用到不少扩展库,把这些扩展库的大量DLL放在软件目录下面,非常不美观. 通过设置自定义的DLL存放目录,可以把DLL存在指定的目录下面. 代码如下: <?xml version ...

  3. php实现简单的上一页下一页

    思路整理: 现在好多人用id的增1和减1实现上一篇和下一篇但是难道文章ID不会断了吗所以你要知道上个ID和个ID是多少就OK了那怎么解决这个问题呢,很简单例子:假如这篇文章的ID200 <a h ...

  4. (Problem 42)Coded triangle numbers

    The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangl ...

  5. 软件包管理_rpm命令管理_yum工具管理_文件归档压缩_源码包管理

    rpm命令管理软件 对于挂载的像U盘那种都会在midea目录下,但是会显示在桌面上 安装软件(i:install,v:verbose冗长的,h:human):rpm  -ivh  xxxx.rpm 安 ...

  6. [置顶] MongoDB 分布式操作——分片操作

    MongoDB 分布式操作——分片操作 描述: 像其它分布式数据库一样,MongoDB同样支持分布式操作,且MongoDB将分布式已经集成到数据库中,其分布式体系如下图所示: 所谓的片,其实就是一个单 ...

  7. ubuntu安装hadoop 若干问题的解决

    问题1:安装openssh-server失败 原因: 下列软件包有未满足的依赖关系: openssh-server : 依赖: openssh-client (= 1:5.9p1-5ubuntu1) ...

  8. Proving Equivalences(加多少边使其强联通)

    Proving Equivalences Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Oth ...

  9. Jsp中使用EL表达式对字符串进行操作

    用fn函数:<%@ taglib prefix="fn" uri="http://Java.sun.com/jsp/jstl/functions" %&g ...

  10. 读取jar包里面的文件

    一.最近做项目的时候,师兄要求读取jar包里面的java文件.在网上查了各种文件以后,终于完成了,在这里和各位朋友分享一下. (一)找到jar包所在的位置. String path="XXX ...