效果图

MainActivity.java

 package com.wangzhen.servicedemo;

 import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.wangzhen.service.MyBindService;
import com.wangzhen.service.MyBindService.MyBinder;
import com.wangzhen.service.MyService;
import com.wangzhen.servicedemo.R; import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder; @ContentView(R.layout.activity_main)
public class MainActivity extends ActionBarActivity { Context mContext; @ViewInject(R.id.Button_StartService)
private Button Button_StartService;
@ViewInject(R.id.Button_StopService)
private Button Button_StopService;
@ViewInject(R.id.Button_BindService)
private Button Button_BindService;
@ViewInject(R.id.Button_unBindService)
private Button Button_unBindService; private MyBindService myBindService; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
ViewUtils.inject(this);
} /**
* 创建ServiceConnection对象
*/
private ServiceConnection connection = new ServiceConnection() { @Override
public void onServiceDisconnected(ComponentName name) {
myBindService = null;
Toast.makeText(mContext, "服务已解除绑定", 2000).show();
} @Override
public void onServiceConnected(ComponentName name, IBinder service) {
myBindService = ((MyBinder) service).getService();
Toast.makeText(mContext, "服务绑定成功,返回值:" + myBindService.getName(),
2000).show();
}
}; @OnClick({ R.id.Button_StartService, R.id.Button_StopService,
R.id.Button_BindService, R.id.Button_unBindService })
private void OnButtonClick(View view) {
Intent intent = new Intent(MainActivity.this, MyService.class);
Intent intent_bind = new Intent(mContext, MyBindService.class);
switch (view.getId()) {
case R.id.Button_StartService:
startService(intent);
break;
case R.id.Button_StopService:
stopService(intent);
break;
case R.id.Button_BindService:
bindService(intent_bind, connection, Context.BIND_AUTO_CREATE);
break;
case R.id.Button_unBindService:
unbindService(connection);
break; default:
break;
}
}
}

MyService.java

 package com.wangzhen.service;

 import java.util.Timer;
import java.util.TimerTask; import com.wangzhen.servicedemo.MainActivity;
import com.wangzhen.servicedemo.R; import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log; /**
*
* @author XX
* @since 2015年7月10日 10:25:56
*/
public class MyService extends Service {
private Context mContext;
private static final int FLAG_SUCCESS = 0;
private static final int FLAG_NUMBER = 1;
private String TAG = "SERVICE";
Timer timer;
private int Count = 0; @Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
flags = START_STICKY;
timer = new Timer();
timer.schedule(new TimerTask() { @Override
public void run() {
// TODO Auto-generated method stub
Message msg = Message.obtain();
msg.what = FLAG_NUMBER;
msg.obj = Count;
mHandler.sendMessage(msg);
Count++;
}
}, 0, 1000); new Thread() {
@Override
public void run() {
super.run();
try {
Thread.sleep(1000);
Message message = Message.obtain();
message.what = FLAG_SUCCESS;
mHandler.sendMessage(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }.start();
return super.onStartCommand(intent, flags, startId);
} @SuppressLint("HandlerLeak")
Handler mHandler = new Handler() {
@SuppressLint("ShowToast")
public void handleMessage(Message msg) {
switch (msg.what) {
case FLAG_SUCCESS:
SendNotification("Service已启动");
break;
case FLAG_NUMBER:
Log.i(TAG, msg.obj.toString());
break; default:
break;
}
}
}; /**
* 发送通知
*
* @param message
*/
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void SendNotification(String message) {
// 点击之后执行的Intent
Intent intent = new Intent(mContext, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
intent, 0);
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.tickerText = "通知";
notification.when = System.currentTimeMillis();
notification.defaults = Notification.DEFAULT_SOUND
| Notification.DEFAULT_VIBRATE;// 设置默认为系统声音
notification.flags = Notification.FLAG_AUTO_CANCEL;// 点击后自动消失
notification.setLatestEventInfo(mContext, "通知", message, pendingIntent); NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mManager.notify(1, notification); } @Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
timer.cancel();
} @Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
} }

MyBindService.java

 package com.wangzhen.service;

 import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; public class MyBindService extends Service { public class MyBinder extends Binder {
/**
* 返回当前Service的实例
*
* @return 当前Service的实例
*/
public MyBindService getService() {
return MyBindService.this;
}
} public String getName() {
return "你好";
} @Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return new MyBinder();
} @Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
} }

StartService与BindService的更多相关文章

  1. Android之startService()和bindService()区别

    1. 生命周期: startService()方式启动,Service是通过接受Intent并且会经历onCreate()和onStart().当用户在发出意图使之销毁时会经历onDestroy(), ...

  2. [转]安卓开发startservice 和bindservice详解

    原文 作者:aikongmeng 来源:安卓中文网 博主暗表:搜到此文,终于为我解惑,bindService并不会真正启动service,不会调用onStartCommand!还需要再bind之前st ...

  3. 深入理解Android的startservice和bindservice

    一.首先,让我们确认下什么是service?         service就是android系统中的服务,它有这么几个特点:它无法与用户直接进行交互.它必须由用户或者其他程序显式的启动.它的优先级比 ...

  4. 理解Android的startservice和bindservice(转)

    一.首先,让我们确认下什么是service? service就是android系统中的服务,它有这么几个特点:它无法与用户直接进行交互.它必须由用户或者其他程序显式的启动.它的优先级比较高,它比处于前 ...

  5. [AndroidTips]startService与bindService的区别

    Service的生命周期方法比Activity少一些,只有onCreate, onStart, onDestroy我们有两种方式启动一个Service,他们对Service生命周期的影响是不一样的. ...

  6. startService与bindService的区别

    转自:http://www.devdiv.com/thread-52226-1-1.html Service的生命周期方法比Activity少一些,只有onCreate, onStart, onDes ...

  7. Android实现简单音乐播放器(startService和bindService后台运行程序)

    Android实现简单音乐播放器(MediaPlayer) 开发工具:Andorid Studio 1.3运行环境:Android 4.4 KitKat 工程内容 实现一个简单的音乐播放器,要求功能有 ...

  8. startService()和bindService()区别

    1. 生命周期:startService()方式启动,Service是通过接受Intent并且会经历onCreate()和onStart().当用户在发出意图使之销毁时会经历onDestroy(),而 ...

  9. 【Android 界面效果34】Android里Service的bindService()和startService()混合使用深入分析

    .先讲讲怎么使用bindService()绑定服务 应用组件(客户端)可以调用bindService()绑定到一个service.Android系统之后调用service的onBind()方法,它返回 ...

随机推荐

  1. C#实现测量程序运行时间及cpu使用时间

    private void ShowRunTime() { TimeSpan ts1 = Process.GetCurrentProcess().TotalProcessorTime; Stopwatc ...

  2. 使用DataSet数据集删除记录

    使用DataSet删除记录和使用DataSet更新记录非常的相似,DataSet删除记录的步骤如下所示. q  创建一个Connection对象. q  创建一个DataAdapter对象. q  初 ...

  3. (我国的省—市—区)三级联动数据库.sql

    # MySQL-Front 5.1  (Build 2.7) /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE */; /*!40101 SET SQL_MODE='' */ ...

  4. sublime text3 安装package control

    20141104日更新的安装代码为 import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c6 ...

  5. python之6-3嵌套函数

    1. 嵌套函数 子函数可以继承父函数的变量 父函数返回子函数 子函数返回结果 看例子如下:结果是一个字符串fun1+fun2 #!/usr/bin/env python # coding=utf-8 ...

  6. ARM的两种启动方式 (NAND FLASH. NOR FLASH)

    为什么会有两种启动方式? 这就是有两种FLASH 的不同特点决定的. NAND FLASH 容量大,存储的单位比特数据的成本要低很多,但是要按照特定的时序对NAND  FLASH  进行读写,因此CP ...

  7. Android扩展 - 拍照篇(Camera)

    1.调用系统摄像头 1.声明常量和变量 2.按钮点击事件,打开系统摄像头 3.重写onActivityResult事件接收拍照返回 4.生成文件名返回路径 5.保存图片 private static  ...

  8. 拉电流(source current)与灌电流(sink current)

    对一个互补输出的驱动器而言,从输出端向外电路流出的负载电流称为拉电流(SOURCE CURRENT):从外电路流入输出端的负载电流称为灌电流(SINK CURRENT):在没有负载的情况下,驱动器本身 ...

  9. Qt在Windows下的三种编程环境搭建

    尊重作者,支持原创,如需转载,请附上原地址:http://blog.csdn.net/libaineu2004/article/details/17363165 从QT官网可以得知其支持的平台.编译器 ...

  10. 鼠标键盘无法进入:(EE) config/hal: couldn’t initialise context: (null)

    vi /var/log/Xorg.0.log 发现有一行:(EE) config/hal: couldn’t initialise context: (null) 在xorg.conf里面加上下面选项 ...