StartService与BindService
效果图
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的更多相关文章
- Android之startService()和bindService()区别
1. 生命周期: startService()方式启动,Service是通过接受Intent并且会经历onCreate()和onStart().当用户在发出意图使之销毁时会经历onDestroy(), ...
- [转]安卓开发startservice 和bindservice详解
原文 作者:aikongmeng 来源:安卓中文网 博主暗表:搜到此文,终于为我解惑,bindService并不会真正启动service,不会调用onStartCommand!还需要再bind之前st ...
- 深入理解Android的startservice和bindservice
一.首先,让我们确认下什么是service? service就是android系统中的服务,它有这么几个特点:它无法与用户直接进行交互.它必须由用户或者其他程序显式的启动.它的优先级比 ...
- 理解Android的startservice和bindservice(转)
一.首先,让我们确认下什么是service? service就是android系统中的服务,它有这么几个特点:它无法与用户直接进行交互.它必须由用户或者其他程序显式的启动.它的优先级比较高,它比处于前 ...
- [AndroidTips]startService与bindService的区别
Service的生命周期方法比Activity少一些,只有onCreate, onStart, onDestroy我们有两种方式启动一个Service,他们对Service生命周期的影响是不一样的. ...
- startService与bindService的区别
转自:http://www.devdiv.com/thread-52226-1-1.html Service的生命周期方法比Activity少一些,只有onCreate, onStart, onDes ...
- Android实现简单音乐播放器(startService和bindService后台运行程序)
Android实现简单音乐播放器(MediaPlayer) 开发工具:Andorid Studio 1.3运行环境:Android 4.4 KitKat 工程内容 实现一个简单的音乐播放器,要求功能有 ...
- startService()和bindService()区别
1. 生命周期:startService()方式启动,Service是通过接受Intent并且会经历onCreate()和onStart().当用户在发出意图使之销毁时会经历onDestroy(),而 ...
- 【Android 界面效果34】Android里Service的bindService()和startService()混合使用深入分析
.先讲讲怎么使用bindService()绑定服务 应用组件(客户端)可以调用bindService()绑定到一个service.Android系统之后调用service的onBind()方法,它返回 ...
随机推荐
- Android --------- 命名规范
工程 软件名称,最好是英文首字母大写:如MobileSafe. 包 企业单位网址的倒序+软件名称:如com.baidu.mobilesafe. 类 类中分为:(头字母小写,其他每个单子首字母大写) 1 ...
- MiniUI学习笔记1
1.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or ...
- 重新认识Intent
相信android开发工程师,对Intent一定不陌生,在整个开发中随时都用到了,今天我们总结一下Intent. 1. 为什么需要Intent? 在android Intent机制是协助应用间的交互与 ...
- 关于控制文件和redo log损坏的恢复
前段时间一朋友自己电脑上的开发测试用的数据库出了点问题,电脑操作系统是Win8,直接在Win8上安装了Oracle11g,后来系统自动升级到Win8.1,Oracle相关的服务全都不见了,想想把数据文 ...
- DHTML【2】--HTML
通过题目,大家已经明确知道,从这一节开始介绍DHTML中的最基础的部分HTML,对于HTML等概念上一节已经做了概述,这一节不再赘余.在学习HTML之前,先告诉大家一个好消息,HTML不难,比C++. ...
- 轻松完成WAP手机网站搭建
用PHPCMS最新发布的V9搭建了PHPCMS研究中心网站(http://phpcms.org.cn)完成后,有用户提出手机访问的问题,于是着手搭建WAP无线站(wap.phpcms.org.cn). ...
- MySQL学习笔记(5) - 修改和删除数据库
1.完整语句 ALTER {DATABASE | SCHEMA} [db_name] [DEFAULT] CHARACHER SET [=] charset_name; 2.修改数据库的编码方式 al ...
- ubuntu openssh-server
1. sudo apt-get install openssh-server 2. sudo service ssh start 3. sudo service ssh status 4. ...
- Linux下*.tar.gz文件解压缩命令 find 命令
1.压缩命令: 命令格式:tar -zcvf 压缩文件名.tar.gz 被压缩文件名 可先切换到当前目录下.压缩文件名和被压缩文件名都可加入路径. 2.解压缩命令: 命令格式:tar -z ...
- python编程中在ubuntu中安装虚拟环境及环境配置
1.升级python包管理工具pip pip install --upgrade pip 备注:当你想升级一个包的时候 `pip install --upgrade 包名` 2.python虚拟环境安 ...