效果图

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. lvs+keepalived+nginx+tomcat

    # 拓扑如下所示 # 节点分布情况 LVS-dr-master eth0: 192.168.146.141 LVS-dr-slave eth0: 192.168.146.142 nginx1: eth ...

  2. js引用类型姿势

    栈 1)var a=new Array(),a.push(a,b,...),a.pop() queue 1)var a=new Array(), a.push(a,b,...),a.shift() a ...

  3. window程序设计1

    int WINAPI WinMain(HINSTANCE HInstance,HINSTANCE HPreInstance,LPSTR szCmdLine,int CmdShown) { Massag ...

  4. 前端技术-svg简介与snap.svg.js开源项目的使用

    前言-为什么学习snap.svg.js 前阵子webAPP的技术群里有人感觉到svg+animate的形式感觉很炫,矢量图任意放大且不需要下载图片,并且在手机端效果流畅. (矢量图与位图最大的区别是, ...

  5. JavaScript加密解密压缩工具

    <script> a=62; function encode() { var code = document.getElementById('code').value; code = co ...

  6. 百度PHP实习一面面试题-算法-二维有序矩阵的查找

    题目描述 有一个二维矩阵,每一行的元素,从左到右保持严格递增,每一列的元素,从上到下保持严格递增.查找给定元素elem,返回NULL或元素位置. 1 3 7 15 16 2 5 8 17 19 3 6 ...

  7. MobileProject

    iOS开源项目MobileProject功能点介绍 一:MobileProject简介 MobileProject项目是一个以MVC模式搭建的开源功能集合,基于Objective-C上面进行编写,意在 ...

  8. 对JAVA的static深刻理解(结合C语言的思考)

    public class statictest { String X = "我是非静态变量"; static int butterfly =0; static String sta ...

  9. android 之 百度地图

    简介 百度地图Android定位SDK为基于移动客户端开发LBS应用提供基础定位能力. 功能介绍 功能介绍: 地图展示:包括2D图.卫星图.3D图地图展示. 地图操作:提供控制平移.缩放.底图旋转.变 ...

  10. Global build settings

    [ ] Select all packages by default *** General build options ***   [ ] Show packages that require gr ...