绑定服务 服务中通过定义Binder对象的子类让这个子类成为桥梁   在onBind()中返回子类对象

这样就可以在activity中调用这个子类的方法

在Activity中通过ServiceConnection获取这个对象并向下转型为该子类对象 y与Activity绑定的服务当Activity结束的时候服务也会跟着结束

timer.cancel()会结束timerTask中的所有任务

NotifyManager.cancel(2)  2是对应的通知的id 会结束对应的通知

 import android.app.Activity;
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 com.qf.service03_bindservice.TimerService.TimerBinder; public class MainActivity extends Activity { //澹版槑Binder瀛愮被瀵硅薄
TimerBinder timerBinder; //3. 瀹炰緥鍖朣erviceConnection鎺ュ彛锛堢粦瀹氭湇鍔$粍浠舵椂浣跨敤鐨勫洖璋冩帴鍙o級
ServiceConnection conn=new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO 缁戝畾鎴愬姛鐨勬柟娉�
timerBinder=(TimerBinder) service;
} @Override
public void onServiceDisconnected(ComponentName name) {
// TODO 涓庣粦瀹氭湇鍔$粍浠舵柇寮�繛鎺ワ紙鍙戠敓鐨勬椂鏈猴細鐢变簬绯荤粺鍘熷洜閫犳垚浜嗘湇鍔$粍浠跺仠姝㈡垨閿�瘉锛� timerBinder=null;
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} public void bindService(View v) {
//缁戝畾鏈嶅姟缁勪欢
bindService(new Intent(getApplicationContext(),TimerService.class),
conn, BIND_AUTO_CREATE); //BIND_AUTO_CREATE鏍囪瘑琛ㄧず锛氱粦瀹氱殑鏈嶅姟缁勪欢濡傛灉涓嶅瓨锛屽垯浼氳嚜鍔ㄥ垱寤猴紝
//娉細鐢眀indService鏂瑰紡鍚姩鐨凷ervice锛屽叾鐢熷懡鍛ㄦ湡浼氬彈鍒扮粦瀹氱粍浠剁殑褰卞搷锛屽嵆褰撶粦瀹氱粍浠禔ctivity閿�瘉鏃讹紝Service涔熶細鍋滄
} public void unbindService(View v) {
unbindService(conn); //瑙i櫎缁戝畾
} public void startTime(View v) {
if(timerBinder!=null){
timerBinder.start();
}
} public void stopTime(View v) {
if(timerBinder!=null){
timerBinder.stop();
}
} }

MainActivity.java

 import java.util.Timer;
import java.util.TimerTask; import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log; public class TimerService extends Service { private Timer timer; //瀹氭椂鍣�
private NotificationManager notifyMgr;
@Override
public void onCreate() {
super.onCreate();
Log.i("debug", "--onCreate--"); timer=new Timer(); notifyMgr=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
} @Override
public IBinder onBind(Intent intent) {
Log.i("debug", "--onBind--");
return new TimerBinder();//2. 瀹炰緥鍖朆inder鐨勫瓙绫伙紝骞惰繑鍥�
} @Override
public boolean onUnbind(Intent intent) {
Log.i("debug", "--onUnbind--");
return super.onUnbind(intent);
} @Override
public void onDestroy() {
Log.i("debug", "--onDestroy--");
super.onDestroy();
} //1. 澹版槑Binder绫荤殑瀛愮被锛岀敤浜嶴ervice涓庣粦瀹氱殑Activity鐨勭粍浠惰繘琛岄�淇�
public class TimerBinder extends Binder{
public void start(){
Log.i("debug", "----start---"); //閫氳繃瀹氭椂鍣紝鏉ュ畨鎺掓椂闂磋鍒�
timer.schedule(new TimerTask(){
@Override
public void run() {
// TODO 鍦ㄦ寚瀹氱殑鏃堕棿鎵ц鐨勪换鍔�
NotificationCompat.Builder builder=
new NotificationCompat.Builder(getApplicationContext());
builder.setSmallIcon(android.R.drawable.ic_menu_today)
.setContentTitle("鎻愰啋")
.setContentText("鏃堕棿浜嗭紝璇ヨ捣搴婁簡....")
.setTicker("鏃堕棿浜嗭紝璇ヨ捣搴婁簡....")
.setDefaults(Notification.DEFAULT_SOUND)
.setOngoing(true); notifyMgr.notify(2, builder.build()); }
},10*1000, 5*1000); } public void stop(){
Log.i("debug", "----stop---");
//鍏抽棴鎵�湁鐨勫畾鏃朵换鍔�
timer.cancel(); notifyMgr.cancel(2);
}
} }

TimerService.java

 <RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <Button
android:id="@+id/btn1Id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="bindService"
android:text="绑定服务" /> <Button
android:id="@+id/btn2Id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn1Id"
android:onClick="unbindService"
android:text="解除绑定" /> <Button
android:id="@+id/btn3Id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn2Id"
android:onClick="startTime"
android:text="开启定时" /> <Button
android:id="@+id/btn4Id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn3Id"
android:onClick="stopTime"
android:text="关闭定时" /> </RelativeLayout>

activity_main.xml

绑定服务-----------binderService TimerTask的使用的更多相关文章

  1. Xamarin.Android广播接收器与绑定服务

    一.前言 学习了前面的活动与服务后,你会发现服务对于活动而言似乎就是透明的,相反活动对于服务也是透明的,所以我们还需要一中机制能够将服务和活动之间架起一座桥梁,通过本节的学习,你将会学到广播与绑定服务 ...

  2. Android(java)学习笔记230:服务(service)之绑定服务的细节

    绑定服务的细节 1. 如果onbind方法返回值是null,onServiceConnect方法就不会被调用: 2. 绑定的服务,在系统设置界面,正在运行条目是看不到的: 3. 绑定的服务,不求同时生 ...

  3. Android(java)学习笔记229:服务(service)之绑定服务调用服务里面的方法 (采用接口隐藏代码内部实现)

    1.接口 接口可以隐藏代码内部的细节,只暴露程序员想暴露的方法 2.利用上面的思想优化之前的案例:服务(service)之绑定服务调用服务里面的方法,如下: (1)这里MainActivity.jav ...

  4. Android(java)学习笔记228:服务(service)之绑定服务调用服务里面的方法

    1.绑定服务调用服务里面的方法,图解: 步骤: (1)在Activity代码里面绑定 bindService(),以bind的方式开启服务 :                     bindServ ...

  5. Android--Service之绑定服务交互

    前言 开篇名义,这篇博客介绍一下Android下使用绑定服务进行时数据交互的几种方法.关于Android下Service的内容,前面两篇博客已经介绍了,不清楚的可以移步过去先看看:Android--S ...

  6. Android应用程序绑定服务(bindService)的过程源代码分析

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6745181 Android应用程序组件Serv ...

  7. Android应用程序绑定服务(bindService)的过程源码分析

    Android应用程序组件Service与Activity一样,既能够在新的进程中启动,也能够在应用程序进程内部启动:前面我们已经分析了在新的进程中启动Service的过程,本文将要介绍在应用程序内部 ...

  8. lvs持久连接及防火墙标记实现多端口绑定服务

    lvs持久连接及防火墙标记实现多端口绑定服务 LVS持久连接: PCC:将来自于同一个客户端发往VIP的所有请求统统定向至同一个RS: PPC:将来自于一个客户端发往某VIP的某端口的所有请求统统定向 ...

  9. Android应用中创建绑定服务使得用户可以与服务交互

    原文:http://android.eoe.cn/topic/android_sdk 一个绑定的服务是客户服务器接口上的一个服务器.一个绑定的服务允许组件(如:活动)来绑定一个服务,传送请求,接收响应 ...

随机推荐

  1. 如何分析 WindowsDump:Dump 起源与初始设置

    https://www.qcloud.com/community/article/511817 转者注:让我感觉以前看蓝屏都白看了~~~原来蓝屏也可以分析具体原因. 适用场景:Windows 系列系统 ...

  2. solr联合多个字段进行检索(multivalued和copyfield的使用)

    在实际工作中不仅仅对索引中的单个字段进行搜索.需要进行综合查询. 比如book表中有id,name(标题),price,summary(摘要),content(内容),我们要找一本书的时候,查询关键字 ...

  3. Python3 引入sqlite3时出现错误:ModuleNotFoundError: No module named '_sqlite3'

    在Python3 中内置了SQLite3,但是在编译安装完之后执行: import sqlite3 出现错误: ModuleNotFoundError: No module named '_sqlit ...

  4. 并发基础(九) java线程的终止与中断

    1.简单了解一下:为何不赞成使用 Thread.stop.Thread.suspend 和 Thread.resume?   suspend .resume.stop方法分别完成了线程的暂停.恢复.终 ...

  5. Python之函数——基础篇

    函数 函数,在BASIC中,叫subroutine(子过程或子程序),在Pascal中叫做procedure(过程)和function,在C中只有function,在Java中叫method. 定义: ...

  6. idea-activate code

    N757JE0KCT-eyJsaWNlbnNlSWQiOiJONzU3SkUwS0NUIiwibGljZW5zZWVOYW1lIjoid3UgYW5qdW4iLCJhc3NpZ25lZU5hbWUiO ...

  7. linux命令--df/ps aux/netstat/hostname/tail

    查询文件系统 df -h 查询cpu使用情况 top 进程查看: ps aux | grep haproxy 端口查看: netstat -lntup 主机名查看 hostname 查看文件末尾字符串 ...

  8. 25. oracle密码过期解决

    解决方法: 1.连接到oracle会自动提示修改数据库密码; 2.如果要设置为数据库密码不过期,可以直接修改: 查看:select * from dba_profiles where profile= ...

  9. jdk配置(备份)

    #####set java environment #export JAVA_HOME=/usr/java/jdk1..0_172 #export JRE_HOME=${JAVA_HOME}/jre ...

  10. ajax 遍历json一维数组

    $.each(data,function(index,value){}data必须是Object类型index是数组的下标value可以是一个对象 function myonclick() { var ...