效果图

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. 【nodejs学习】1.文件操作

    1.小文件拷贝,使用nodejs内置模块 var fs = require('fs'); function copy(src, dst){ fs.writeFileSync(dst, fs.readF ...

  2. EasyUi DataGrid中数据编辑方式及编辑后数据获取,校验处理

    EasyUi中的DataGrid提供前台编辑的相关函数. 实现客户选中DataGrid中一列后,对选中列中的一个字段进行编辑,并对数据进行实时校验后,传递至后台保存的需求, 主要涉及到DataGrid ...

  3. PHP扩展开发(2) - VS2013环境搭建

    1. 安装VS2013 2. Cygwin安装 3. 下载Windows的PHP源码 4. 修改~/ext/ext_skel_win32.php     加上 $cygwin_path = 'c:\c ...

  4. How many ways??(HDU 2157)

    How many ways?? Sample Input 4 4 //n个点,m条路径0 1 //s->t可通0 21 32 32 //询问数0 3 2 //从0到3走两条路可到的方案有多少种0 ...

  5. EasyUI datagrid简单运用

    jquery的前端框架挺多的,有easyUI ,bootstrap...,对于做系统软件或许easyUI比较好,因为里面控件很丰富,而bootstrap非常简洁大方,但是控件相 对比较少,特别是复杂的 ...

  6. swift闭包-备

    我给Swift 中的闭包一个定义:闭包是自包含的匿名函数代码块,可以作为表达式.函数参数和函数返回值,闭包表达式的运算结果是一种函数类型. Swift中的闭包类似于Objective-C中的代码块.J ...

  7. Codeforces 459E Pashmak and Graph

    http://www.codeforces.com/problemset/problem/459/E 题意: 给出n个点,m条边的有向图,每个边有边权,求一条最长的边权上升的路径的长度. 思路:用f存 ...

  8. CentOs6.5中安装和配置vsftp简明

    这篇文章主要介绍了CentOs6.5中安装和配置vsftp简明教程,需要的朋友可以参考下     一.vsftp安装篇 复制代码代码如下: # 安装vsftpdyum -y install vsftp ...

  9. python sqlite3使用

    python sqlite3文档地址:http://docs.python.org/2/library/sqlite3.html The sqlite3 module was written by G ...

  10. 找出最小的k个数

    •已知数组中的n个正数,找出其中最小的k个数. •例如(4.5.1.6.2.7.3.8),k=4,则最小的4个数是1,2,3,4 •要求: –高效: –分析时空效率 •扩展:能否设计出适合在海量数据中 ...