一、启动Service并传递参数

传递参数时只需在startService启动的Intent中传入数据便可,接收参数时可在onStartCommand函数中通过读取第一个参数Intent的内容来实现

1.MainActivity.java

package com.example.shiyanshi.serviceconnected;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText; public class MainActivity extends Activity implements View.OnClickListener {
private EditText editText; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); editText= (EditText) findViewById(R.id.editText);
findViewById(R.id.btnStartService).setOnClickListener(this);
findViewById(R.id.btnStopService).setOnClickListener(this);
} @Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnStartService:

Intent intent=new Intent(MainActivity.this,MyService.class);
intent.putExtra("data",editText.getText().toString());
startService(intent);

                break;
case R.id.btnStopService:
stopService(new Intent(MainActivity.this,MyService.class));
} }
}

2.MyService.java

package com.example.shiyanshi.serviceconnected;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder; public class MyService extends Service {
private String data;
private boolean flag; public MyService() {
} @Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
} @Override
public int

onStartCommand

(Intent intent, int flags, int startId) {

data=intent.getStringExtra("data");

        return super.onStartCommand(intent, flags, startId);
} @Override
public void onCreate() {
super.onCreate();
flag=true;
new Thread() {
@Override
public void run() {
super.run();
while (flag) {
System.out.println(data);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
} @Override
public void onDestroy() {
super.onDestroy();
flag=false;
}
}

3.布局文件

<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <EditText android:text="@string/hello_world" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/editText"/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动服务"
android:id="@+id/btnStartService" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止服务"
android:id="@+id/btnStopService" /> </LinearLayout>

二、绑定Service进行通信

(1)Activity向Service传递消息

绑定服务后,Activity和Service之间可以通过android.os.Binder进行通信,当绑定服务时首先调用onCreate函数,然后调用Service类的onBind函数返回一个Binder,之后会调用Activity类中实现的onServiceConnected函数,该函数的第二个参数IBinder iBinder是Service类中onBind方法的返回值,通过这个Binder二者便可以成功通信。

1.MainActivity.java

package com.example.shiyanshi.serviceconnected;

import android.app.Activity;
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.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText; public class MainActivity extends Activity implements View.OnClickListener, ServiceConnection {
private EditText editText;
private MyService.Binder binder=null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); editText= (EditText) findViewById(R.id.editText);
findViewById(R.id.btnStartService).setOnClickListener(this);
findViewById(R.id.btnStopService).setOnClickListener(this);

findViewById(R.id.btnBindService).setOnClickListener(this);
findViewById(R.id.btnUnbindService).setOnClickListener(this);
findViewById(R.id.btnSyncData).setOnClickListener(this);

    }

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId(); //noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} return super.onOptionsItemSelected(item);
} @Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnStartService:
Intent intent=new Intent(MainActivity.this,MyService.class);
intent.putExtra("data",editText.getText().toString());
startService(intent);
break;
case R.id.btnStopService:
stopService(new Intent(MainActivity.this, MyService.class));
break;

case R.id.btnBindService:
bindService(new Intent(MainActivity.this, MyService.class), this, Context.BIND_AUTO_CREATE);
break;
case R.id.btnUnbindService:
unbindService(this);
break;
case R.id.btnSyncData:
if(binder!=null){
System.out.println("bind in not null");
binder.setData(editText.getText().toString()); //调用Bind中实现的数据交互方法
}
break;

        }

    }

    @Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
System.out.println("*****Connected Successful*******");

binder= (MyService.Binder) iBinder;

    }

    @Override
public void onServiceDisconnected(ComponentName componentName) {
System.out.println("*****Disconnected Successful*******"); }
}

2.MyService.java

package com.example.shiyanshi.serviceconnected;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; public class MyService extends Service {
private String data="default info";
private boolean flag; public MyService() {
} @Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");

return new Binder(); //返回值会传给onServiceConnected函数的第二个参数IBinder

    }   
    //该类是Activity和Service进行交互数据的接口

public class Binder extends android.os.Binder{
public void setData(String data) {
MyService.this.data=data;
}

    }

    @Override
public int onStartCommand(Intent intent, int flags, int startId) { data=intent.getStringExtra("data");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onCreate() {
super.onCreate();
System.out.println("*******onCreate********");
flag=true;
new Thread() {
@Override
public void run() {
super.run();
while (flag) {
System.out.println(data);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
} @Override
public void onDestroy() {
super.onDestroy();
System.out.println("******onDestroy******");
flag=false;
}
}

(2)Service向Activity传递消息,并将传递的数据显示到Activity中

主要通过在Service中设定一个回调函数的接口,并定义一个该接口的引用,该引用的实例化是在Activity中进行的,实例化的同时会重写该接口中定义的回调函数,让该回调函数发送一个消息,并且在消息处理器(Handler)中进行更新UI线程的内容;此外在新开的Thread线程中调用该回调函数进行更新数据。

1.MainActivity.java

package com.example.shiyanshi.serviceconnected;

import android.app.Activity;
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.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView; import org.w3c.dom.Text; import java.util.logging.Handler; public class MainActivity extends Activity implements View.OnClickListener, ServiceConnection {
private EditText editText;
private MyService.Binder binder=null;
private TextView tvOut; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); editText= (EditText) findViewById(R.id.editText);
tvOut=(TextView)findViewById(R.id.tvOut); findViewById(R.id.btnStartService).setOnClickListener(this);
findViewById(R.id.btnStopService).setOnClickListener(this);
findViewById(R.id.btnBindService).setOnClickListener(this);
findViewById(R.id.btnUnbindService).setOnClickListener(this);
findViewById(R.id.btnSyncData).setOnClickListener(this); } @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId(); //noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} return super.onOptionsItemSelected(item);
} @Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnStartService:
Intent intent=new Intent(MainActivity.this,MyService.class);
intent.putExtra("data",editText.getText().toString());
startService(intent);
break;
case R.id.btnStopService:
stopService(new Intent(MainActivity.this, MyService.class));
break;
case R.id.btnBindService:
bindService(new Intent(MainActivity.this, MyService.class), this, Context.BIND_AUTO_CREATE);
break;
case R.id.btnUnbindService:
unbindService(this);
break;
case R.id.btnSyncData:
if(binder!=null){
System.out.println("bind in not null");
binder.setData(editText.getText().toString());
}
break;
} } @Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
System.out.println("*****Connected Successful*******");
binder= (MyService.Binder) iBinder;

//设置回调函数,在回调函数中通过发送消息和消息处理器进行修改UI线程要显示的内容
binder.getService().setCallback(new MyService.Callback() {
@Override
public void onDataChange(String data) {
//tvOut.setText(data); 这里不可以直接设置,因为由新创建的线程去调用这个函数,不允许直接修改UI线程的内容
Message msg=new Message();
Bundle bundle=new Bundle();
bundle.putString("data",data);
msg.setData(bundle);
handler.sendMessage(msg); //通过handler发送消息
}
});

    }

    @Override
public void onServiceDisconnected(ComponentName componentName) {
System.out.println("*****Disconnected Successful*******"); }
 

//消息处理函数,接收Message并进行处理

    

private android.os.Handler handler=new android.os.Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
tvOut.setText(msg.getData().getString("data"));

}
};

}
 

2.MyService.java

package com.example.shiyanshi.serviceconnected;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder; public class MyService extends Service {
private String data="default info";
private boolean flag; public MyService() {
} @Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
System.out.println("******onBind*****");
return new Binder(); //返回值会传给onServiceConnected函数的第二个参数IBinder
}
//该类是Activity和Service进行交互数据的接口
public class Binder extends android.os.Binder{
public void setData(String data) {
MyService.this.data=data;
}

//获取当前的MyService类的引用
public MyService getService(){
return MyService.this;
}

    }

    @Override
public int onStartCommand(Intent intent, int flags, int startId) { data=intent.getStringExtra("data");
return super.onStartCommand(intent, flags, startId);
} @Override
public void onCreate() {
super.onCreate();
System.out.println("*******onCreate********");
flag=true; new Thread() {
@Override
public void run() {
super.run();
int i=0;
while (flag) {
i++;
String str=i+":"+data;
System.out.println(str);

//由新创建的线程去调用这个函数,不允许直接修改UI线程的内容
if (callback!=null){
callback.onDataChange(str);
}

                    try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
} @Override
public void onDestroy() {
super.onDestroy();
System.out.println("******onDestroy******");
flag=false;
}

//创建的接口用于回调,回调函数(onDataChange)具体是在Activity中实现的


private Callback callback=null;

public void setCallback(Callback callback) {
this.callback = callback;
}

public Callback getCallback() {
return callback;
}

public static interface Callback{
void onDataChange(String data);
}


}
 
 

(六)Android中Service通信的更多相关文章

  1. Android中Service通信(二)——绑定Service进行通信

    一.把输入文本的数据同步到服务的实例(如何执行服务的内部代码) 绑定服务比启动服务更加方便高效,绑定服务中的直接方法调用比Intent作为载体传输更为快捷得多. 1.activity_main.xml ...

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

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

  3. Android中Service(服务)详解

    http://blog.csdn.net/ryantang03/article/details/7770939 Android中Service(服务)详解 标签: serviceandroidappl ...

  4. Android中Service的使用详解和注意点(LocalService)

    Android中Service的使用详解和注意点(LocalService) 原文地址 开始,先稍稍讲一点android中Service的概念和用途吧~ Service分为本地服务(LocalServ ...

  5. Android中Service的一个Demo例子

    Android中Service的一个Demo例子  Service组件是Android系统重要的一部分,网上看了代码,很简单,但要想熟练使用还是需要Coding.  本文,主要贴代码,不对Servic ...

  6. Android中Service与多个Activity通信

    由于项目需要,我们有时候需要在service中处理耗时操作,然后将结果发送给activity以更新状态.通常情况下,我们只需要在一个service与一个activity之间通信,通常这种情况下,我们使 ...

  7. Android中Service和Activity之间的通信

    启动Service并传递数据进去: Android中通过Intent来启动服务会传递一个Intent过去. 可以在Intent中通过putExtra()携带数据 Intent startIntent ...

  8. Android中Service 使用详解(LocalService + RemoteService)

    Service 简介: Service分为本地服务(LocalService)和远程服务(RemoteService): 1.本地服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外L ...

  9. Android中AIDL通信机制分析

    一.背景 ·1.AIDL出现的原因 在android系统中,每一个程序都是运行在自己的进程中,进程之间无法进行通讯,为了在Android平台,一个进程通常不能访问另一个进程的内存空间,所以要想对话,需 ...

随机推荐

  1. ARM9嵌入式学习笔记(2)-Vi使用

    ARM9嵌入式学习笔记(2) 实验1-1-3 Vi使用 vi创建文件vi hello.c:vi smb.conf-打开文件smb.conf i键-插入模式:esc键-命令行模式::-底行模式: 底行模 ...

  2. kafka中处理超大消息的一些考虑

    Kafka设计的初衷是迅速处理短小的消息,一般10K大小的消息吞吐性能最好(可参见LinkedIn的kafka性能测试).但有时候,我们需要处理更大的消息,比如XML文档或JSON内容,一个消息差不多 ...

  3. heroku

    一个可以在上面部署自己的应用一个共享平台,例如可以部署访问google的代理 地址为:https://www.heroku.com/

  4. angular controller之间通信方式

    对于日常开发中,难免会有controller之间通信需求.对于controller之间通信有两种方式可以做到. 用 Angular 进行开发,基本上都会遇到 Controller 之间通信的问题,本文 ...

  5. Opencv--HoughCircles源码剖析

    图形可以用一些参数进行表示,标准霍夫变换的原理就是把图像空间转换成参数空间(即霍夫空间),例如霍夫变换的直线检测就是在距离-角度空间内进行检测.圆可以表示成: (x-a)2+(y-b)2=r2     ...

  6. js常用正则表达式汇总

    常用的前台正则表达式汇总. 1.手机号验证 手机格式以1开头,现有的手机格式一般为13.14.15.17.18等 var regMobile = /^1[34578]\d{9}$/; //或者为/^1 ...

  7. java替换字符串和用indexof查找字符

    java自带替换 String s="hlz_and_hourui哈哈"; String new_S=s.replaceAll("哈", "笑毛&qu ...

  8. 简单的oracle sql 语句

    创建表空间 create tablespace qnhouse --表空间文件路径 datafile 'E:\qnhost\qnhouse.dbf' --表空间文件大小 size 100M; 创建用户 ...

  9. oracle add_months函数的用法详解

    如果需要取上一个月的数据,并且每天都要进行此操作,每次都需要改时间,的确非常的麻烦,所以想到了oracle add_months函数这个函数 oracle add_months函数: oracle a ...

  10. TextArea里Placeholder换行问题

    页面上使用TextArea控件时,会时不时的想给个提示,比如按照一定方式操作之类的.正常情况下,会使用Placeholder,但这样的提示是不会换行的,无论是用\r\n,还是用<br/>, ...