效果图

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. 2.RxJava详解网址http

    RxJava 到底是什么 RxJava 好在哪 API 介绍和原理简析 1) Scheduler 的 API (二) 2) Scheduler 的原理(二) 3) 延伸:doOnSubscribe() ...

  2. Mongodb基本操作之.net

    1.下载官方for C#驱动 2.导入2个dll文件 3.连接字符串 <add key="MongoConn" value="mongodb://127.0.0.1 ...

  3. dijkstra堆优化模板

    #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #in ...

  4. Python实现合并排序MergeSort

    def merge(sort_list, start, mid, end): left_list = sort_list[start:mid] right_list = sort_list[mid:e ...

  5. k-means均值聚类算法(转)

    4.1.摘要 在前面的文章中,介绍了三种常见的分类算法.分类作为一种监督学习方法,要求必须事先明确知道各个类别的信息,并且断言所有待分类项都有一个类别与之对应.但是很多时候上述条件得不到满足,尤其是在 ...

  6. c语言,全局变量,局部变量,外部函数,内部函数,stasic和extern的复习总结

    @import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/c ...

  7. cf B. Dima and Text Messages

    http://codeforces.com/contest/358/problem/B 先按照题意说的构造一个字符串s,然后与对比的字符串T比较,看看在字符串T中顺序查找有没有字符串S的所有字符,有输 ...

  8. HTTP methods 与 RESTful API

    Note GET, primarily used to select resources. Other options for an API method include: POST, primari ...

  9. Delphi TcxTreelist 设置scrollbars 不起作用的原因

    最近设置TcxTreelist的滚动条,发现水平的不起作用, 即使设置 sboth也不起作用. 查找,发现设置的一些属性导致了这个原因, 建立备忘,如下图: 1.属性, 这个页面,设置的表格,怎么也看 ...

  10. HDU4893--Wow! Such Sequence! (线段树 延迟标记)

    Wow! Such Sequence! Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Oth ...