在Service里面装数据,从Activity里面用serviceConnection取数据

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.chenshuai.myapplication.ActivityService"
android:orientation="vertical"> <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="测试普通服务"
android:textSize="30sp"/> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"> <Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="一般启动服务"
android:onClick="yibanqdonclick"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="一般停止服务"
android:onClick="yibantzonclick" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="测试绑定服务"
android:textSize="30sp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"> <Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="绑定启动服务"
android:onClick="bangdingqdonclick"/> <Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="读取服务"
android:onClick="duqusjonclick"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="绑定停止服务"
android:onClick="bangdingtzonclick" />
</LinearLayout> </LinearLayout>

Service

package com.example.chenshuai.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log; public class MyService_1 extends Service {
public MyService_1() { //构造方法里测试
Log.e("TAG","构造Service");
} int i = 0; Boolean aBoolean = true;
//自定义类,继承Binder,装数据
public class Mybinder extends Binder
{
public int getText()
{
return i;
}
} //绑定的回调方法
//必须要重写
@Override
public IBinder onBind(Intent intent) {
//绑定方法
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
Log.e("TAG","绑定并调用");
//return new Binder(); //启动子线程,改变i的值
new Thread()
{
public void run()
{
while (aBoolean)
{
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
} i++;
}
}
}.start(); return new Mybinder();
} @Override
public void onCreate() { //创建方法
Log.e("TAG","创建Service");
super.onCreate();
} @Override
public void onDestroy() {
//销毁方法
Log.e("TAG","销毁Service");
super.onDestroy();
} @Override
public int onStartCommand(Intent intent, int flags, int startId) { //
Log.e("TAG","启动命令Command");
return super.onStartCommand(intent, flags, startId);
}
//解绑时候调用 @Override
public boolean onUnbind(Intent intent) { Log.e("TAG","解除绑定"); //停止循环
aBoolean = false;
return super.onUnbind(intent);
}
}

java

package com.example.chenshuai.myapplication;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast; public class ActivityService extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_service);
} //普通方式启动Service
//参考Activity的启动方式
public void yibanqdonclick(View view)
{
//通过意图
//显示意图
Intent intent = new Intent(this,MyService_1.class);
startService(intent); Toast.makeText(ActivityService.this, "启动Service", Toast.LENGTH_SHORT).show();
}
public void yibantzonclick(View view)
{
//通过意图
//显示意图
Intent intent = new Intent(this,MyService_1.class);
stopService(intent); Toast.makeText(ActivityService.this, "启动Service", Toast.LENGTH_SHORT).show();
}
ServiceConnection serviceConnection; MyService_1.Mybinder mybinder; public void bangdingqdonclick(View view)
{
Intent intent = new Intent(this,MyService_1.class); //实现ServiceConnection接口
if (serviceConnection == null) {
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) { Log.e("TAG", "连接服务"); //接收数据 Mybinder
mybinder = (MyService_1.Mybinder)service; } //异常断开才会调用
@Override
public void onServiceDisconnected(ComponentName name) { Log.e("TAG", "断开连接"); }
};
}
//参数:意图,连接,连接方式 BIND_AUTO_CREATE自动创建
bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE); Toast.makeText(ActivityService.this, "连接服务成功", Toast.LENGTH_SHORT).show();
} public void bangdingtzonclick(View view)
{
//判断是否已经绑定,连接是否为空
if (serviceConnection != null)
{
//解除绑定
unbindService(serviceConnection); serviceConnection = null; Toast.makeText(ActivityService.this, "解除绑定", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(ActivityService.this, "尚未绑定", Toast.LENGTH_SHORT).show();
}
} //读取服务数据
public void duqusjonclick(View view)
{
//调用服务对象的方法
if (mybinder != null)
{
Toast.makeText(ActivityService.this, "读取的信息是:"+mybinder.getText(), Toast.LENGTH_SHORT).show();
} } //重写回调方法,防止强制退出时,绑定服务还在运行
@Override
protected void onDestroy() { if (serviceConnection != null) {
//解除绑定
unbindService(serviceConnection); serviceConnection = null;
}
super.onDestroy();
}
}

manifest.xml

 <service
android:name=".MyService_1"
android:enabled="true"
android:exported="true" />

Android——Service装取数据的更多相关文章

  1. Android MaoZhuaWeiBo开发Service抓取个人信息-2

    前面把基本的东西讲完了,之后就是数据的获取和解析显示出来了,那接下来我们就负责抓取数据的这块吧,首先我们须要 在清单文件中载入服务和活动 加入:. <activity android:name= ...

  2. Android中Service通信(一)——启动Service并传递数据

    启动Service并传递数据的小实例(通过外界与服务进行通信): 1.activity_main.xml: <EditText android:layout_width="match_ ...

  3. Android移动网络如何抓取数据包

    1)下载tcpdump工具 tcpdump(dump the traffic on a network)是Linux中强大的网络数据采集分析工具之一,可以将网络中传送的数据包头完全截获下来提供分析.它 ...

  4. 浅谈android Service和BroadCastReceiver

    1.题记 Android中的服务和windows中的服务是类似的东西,服务一般没有用户操作界面,它运行于系统中不容易被用户发觉,可以使用它开发如监控之类的程序. 广播接收者(BroadcastRece ...

  5. 多线程查询数据,将结果存入到redis中,最后批量从redis中取数据批量插入数据库中【我】

    多线程查询数据,将结果存入到redis中,最后批量从redis中取数据批量插入数据库中 package com.xxx.xx.reve.service; import java.util.ArrayL ...

  6. android应用安全——(数据抓包)跟踪监控android数据包

    转载博客:http://blog.csdn.net/xyz_lmn/article/details/8808169 web开发中Chrome.IE.firefox等浏览器都自带提供了插件帮助开发者跟踪 ...

  7. Android Service完全解析,关于服务你所需知道的一切(下)

    转载请注册出处:http://blog.csdn.net/guolin_blog/article/details/9797169 在上一篇文章中,我们学习了Android Service相关的许多重要 ...

  8. Android Service完全解析,关于服务你所需知道的一切(上)

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/11952435 相信大多数朋友对Service这个名词都不会陌生,没错,一个老练的A ...

  9. android service 的各种用法(IPC、AIDL)

    http://my.oschina.net/mopidick/blog/132325 最近在学android service,感觉终于把service的各种使用场景和用到的技术整理得比较明白了,受益颇 ...

随机推荐

  1. [转] spring的普通类中如何取session和request对像

    在使用spring时,经常需要在普通类中获取session,request等对像.比如一些AOP拦截器类,在有使用struts2时,因为struts2有一个接口使用org.apache.struts2 ...

  2. es5 温故而知新 简单继承示例

    // 矩形(构造器/父类) function Rectangle (height, width) { this.height = height; this.width = width; } // 获取 ...

  3. java appium webview切换处理

    Set<String> contexts = driver.getContextHandles(); for(String item :contexts){ // NATIVE_APP / ...

  4. ||在oracle数据库中起到字符串拼接的作用

    例子:select org.id from org where inner_code like '12011601001' || '%' ||在oracle数据库中起到字符串拼接的作用,上面等同于'1 ...

  5. Eclipse 快速提取一个方法 (重构)

    选择一块代码并将其转换为一个方法.Eclipse 会自动地推知方法参数及返回类型. 我们有的时候方法太大,但是自己复制粘贴重构又比较麻烦 eclispe拥有这个功能 alt+shift+m 也可以右键 ...

  6. FFT节省资源的思路

    作者:桂. 时间:2017-01-18  23:07:50 链接:http://www.cnblogs.com/xingshansi/articles/6298391.html 前言 FFT是信号处理 ...

  7. C#中 如何处理 JSON中的特殊字符

    public static String StringToJson(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0 ...

  8. hdoj 1874 畅通project续【SPFA】

    畅通project续 Time Limit : 3000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other) Total Su ...

  9. 对于android浏览器的一些看法

    首先我先声明我不是一个浏览器开发者,只是近段时间看了一些关于浏览器的东西,才有一些看法. 在几年前开发手机的web 页面,都经常因为JS插件不兼容android WebView内核,导致开发浪费大量时 ...

  10. SQL Server 2008 添加登录账户 配置权限

    首先打开数据库,并以windows身份验证模式扥牢固数据库, 然后在左侧的[对象资源管理器中]展开[安全性]节点,鼠标右键点击节点中的[登录名],在弹出的菜单中单击[新建登录名],弹出如图对话框: 然 ...