效果图:

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. gridview回顾

    第一看asp.net是在做项目之前,感觉收获也很大,第二次看gridview是在做完项目之后对GridView的回顾,这次的感觉是:我需要多想点,知识直到用时方觉少.直入正题吧,看gridview. ...

  2. monkeyrunner学习--手机按键

    按下HOME键 device.press('KEYCODE_HOME','DOWN_AND_UP') 按下BACK键 device.press('KEYCODE_BACK','DOWN_AND_UP' ...

  3. R语言学习笔记之外部文件读取

    在win32位的系统下,RODBC包内的函数是可以直接运行的,但在win64位的系统则不支持! 1.读取外部文件read.table()---csv,txt,excel 最基本函数是read.tabl ...

  4. python自学笔记(六)二进制与位移

    一.二进制 a = 1 bin(a)-->ob1  #python内置方法 ob 表示二进整型制格式 二.难缠符号 1.位移二进制的位 >> 右位移,想象成 切肉切去最后一位 例如 ...

  5. 从基因组可视化工具——circos说起,circos安装

      这是博客改版的第一篇博文,选择最近使用的生物信息学软件——circos开始写起.circos是用perl写的生物软件,从发表的文章来看 学习circos主要是熟悉配置文件的编辑方法,搞清楚其中的标 ...

  6. JS声明语句提升与作用域

    <!DOCTYPE html><html><head></head><body><script>//-------------- ...

  7. BZOJ 2463 谁能赢呢? (博弈论)

    题解:简单博弈论 #include <cstdio> int main(){ int n; while(scanf("%d",&n),n!=0) if (n&a ...

  8. dojo 学习笔记

    1  因为Dijit包括了一系列的UI组件,他绑定了4个支持的主题:nihilo, soria, tundra 和claro.每个主题包括了一系列的图片和CSS文件来控制组件的外观.CSS文件必须显示 ...

  9. codeforces#FF DIV2C题DZY Loves Sequences(DP)

    题目地址:http://codeforces.com/contest/447/problem/C C. DZY Loves Sequences time limit per test 1 second ...

  10. Linux-中断和中断处理

    1.中断 #中断使得硬件得以发出通知给处理器,本质上是一种电信号 #中断随时能够产生.内核随时会被打断 #不同设备的中断不同,每一个中断都通过一个唯一的数字标识.称为IRQ(中断请求) 2.中断处理程 ...