Android app:回调方式实现Service向activity传递数据
一、开启服务的时候,如果我们是通过bindService来绑定服务并且要向服务传递数据,可以直接在Intent中设置bundle来达到效果,但是如果是我们需要从服务中返回一些数据到Activity中的时候,实现起来就有各种各样的方法,比如说使用回调,使用广播等等,今天说的是使用回调的方法。
二、测试源码
1、布局文件\interfaceservicecallback\app\src\main\res\layout\activity_main.xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvOut"
android:layout_width="wrap_content"
android:layout_height="150dp"
android:textSize="50dp"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btnBindService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start service"
tools:layout_editor_absoluteX="129
tools:layout_editor_absoluteY="128dp" />
</android.support.constraint.ConstraintLayout>
2、com/example/interfaceservicecallback/MainActivity.java
package com.example.interfaceservicecallback;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {
private TextView tvOut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvOut = (TextView) findViewById(R.id.tvOut);
findViewById(R.id.btnBindService).setOnClickListener(this);
}
@Override
public void onClick(View v) {
bindService(new Intent(this, MyService.class), this, BIND_AUTO_CREATE);
} @Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.Binder binder = (MyService.Binder) service;
MyService myService = binder.getService();
myService.setCallback(new MyService.Callback() {
@Override
public void onDataChange(String data) {
Message msg = new Message();
msg.obj = data;
handler.sendMessage(msg);
}
});
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
tvOut.setText(msg.obj.toString());
}
};
}
3、service文件com/example/interfaceservicecallback/MyService.java
package com.example.interfaceservicecallback;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.support.annotation.Nullable;
import android.util.Log;
public class MyService extends Service {
private boolean connecting = false;
private Callback callback;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new Binder();
}
public class Binder extends android.os.Binder {
public MyService getService() {
return MyService.this;
}
}
@Override public void onCreate() {
super.onCreate();
connecting = true;
new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (connecting == true) {
i++;
if (callback != null) {
callback.onDataChange(i + "");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public void setCallback(Callback callback) {
this.callback = callback;
}
public static interface Callback {
void onDataChange(String data);
}
@Override
public void onDestroy() {
super.onDestroy();
connecting = false;
}
}
4、声明service,app/src/main/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.interfaceservicecallback">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService">
</service>
</application>
</manifest>
5、app运行效果

6、源码下载地址:https://download.csdn.net/download/qq_37858386/11987940
Android app:回调方式实现Service向activity传递数据的更多相关文章
- Android开发学习之路-回调实现Service向activity传递数据
开启服务的时候,如果我们是通过bindService来绑定服务并且要向服务传递数据,可以直接在Intent中设置bundle来达到效果,但是如果是我们需要从服务中返回一些数据到Activity中的时候 ...
- Android开发:向下一个activity传递数据,返回数据给上一个activity
1.向下一个activity传递数据 activity1 Button button=(Button) findViewById(R.id.button1); button.setOnClickLis ...
- 核心基础以及Fragment与Activity传递数据完整示例
MainActivity如下: package cc.testsimplefragment0; import android.os.Bundle; import android.app.Activit ...
- Fragment与Activity传递数据
MainActivity如下: package cc.testsimplefragment0; import android.os.Bundle; import android.app.Activit ...
- Android使用JNI实现Java与C之间传递数据(转)
介绍Java如何将数据传递给C和C回调Java的方法. java传递数据给C,在C代码中进行处理数据,处理完数据后返回给java.C的回调是Java传递数据给C,C需要用到Java中的某个方法,就需 ...
- Android使用JNI实现Java与C之间传递数据
介绍Java如何将数据传递给C和C回调Java的方法. java传递数据给C,在C代码中进行处理数据,处理完数据后返回给java.C的回调是Java传递数据给C,C需要用到Java中的某个方法,就需要 ...
- Fragment+Activity传递数据
自己经常使用的知识点,每次到要用的时候都还要再查一次才能懂得使用,终于体会到总结的必要性了. Activity传递数据给Fragment Bundle bundle_fragment=new Bund ...
- Android Service实时向Activity传递数据
演示一个案例,需求如下:在Service组件中创建一个线程,该线程用来生产数值,每隔1秒数值自动加1,然后把更新后的数值在界面上实时显示. 步骤如下:1.新建一个android项目工程,取名为demo ...
- Service实时向Activity传递数据案例
转自 http://www.cnblogs.com/linjiqin/p/3147764.html 演示一个案例,需求如下:在Service组件中创建一个线程,该线程用来生产数值,每隔1秒数值自动加1 ...
- Android Activity 传递数据
activity中数据的传递方式有2中,一种是使用putExtra()传递,另外一种是传递Bundle对象,使用putExtras()方法. 方法一 发送数据 putExtra()传送的是键值对,第一 ...
随机推荐
- influxdb数据库结构小结
转载请注明出处: InfluxDB 是一个开源的时序型数据库,它的数据主要存储在三个文件夹中:data.meta 和 wal. data 文件夹:这个文件夹存储的是 InfluxDB 的数据文件,也称 ...
- 使用ProWindow时,控制按钮状态的说明
在Pro SDK中,提供了一个默认的窗口基类,ProWindow Class,提供了基础的窗体样式,可供扩展和调用. 有网友问我,在使用时,会发现窗体右上角的控制按钮,有时会没有按照自己的预期显示. ...
- 一图一知-vue强大的slot
vue常用的slot知识点记录
- 【Amadeus原创】华为一键强制关闭后台应用的终极解决方法
华为手机速度是快,用起来很顺手,但是最让人头疼的,就是紧急情况开会,我音乐关不了. 上划把全部应用删掉,也没用. 经过一阵子摸索,发现终极办法: 1, 打开华为自带的 手机助手- 应用启动管理 2, ...
- 依赖注入在 dotnet core 中实现与使用:5. 使用支持 Unicode 的 HtmlEncoder
现象 在 ASP.NET Core MVC 中,当在页面中传递了一个包含中文字符串到页面的时候,页面的显示是正常的,但是如果查看页面源码,却看不到中文,变成了一串编码之后的内容. 例如,在页面中直接定 ...
- JEP 457 Java 22:Class-File API
查看 Java 22:Class-File API | 作者:Ben Weidig | 2024 年 4 月 | Medium 终于有一个和 DLR 相当的官方库了.
- Mapstruct使用时报Unknown property xxx in result type xxx. Did you mean null
0.背景 使用mapstruct时出现: Unknown property "xxx" in result type xxx. Did you mean "null&qu ...
- baomidou的dynamic-datasource读写分离实现和加入AOP根据方法名选择库
文档 https://gitee.com/baomidou/dynamic-datasource-spring-boot-starter/wikis/pages maven <depende ...
- IPV6禁用导致 RabbitMQ 无法启动的问题
问题现象 在开发的过程中遇到了 RabbitMQ 怎么也启动不起来的现象.查看 RabbitMQ 自身的启动日志,并没有发现有什么有用的报错信息,只是从某天开始就一直在打印重启的日志,尝试多次重启也不 ...
- Qt编写物联网管理平台44-告警邮件转发
一.前言 上一篇文章说的是告警短信发送,这种效率非常高,缺点也很明显,需要购买特定的短信硬件设备支持才行,而且每条短信都要收费,如果要求发送的短信数量特别多,这个费用常年累月下来也是不少的,客户就不愿 ...