Android Service与Activity通信

来源:互联网 发布:淘宝心选在哪里设置 编辑:程序博客网 时间:2024/05/22 04:50

通过Binder+回调方式实现Service到Activity的通信,当然也可以使用广播的方式来通知Activity,这里用第一种方式

Service:


package com.example.test;import java.util.Random;import android.app.Service;import android.content.Intent;import android.os.IBinder;/** * 服务 * @author HTP * */public class MyService extends Service {private boolean running = true;@Overridepublic IBinder onBind(Intent arg0) {// TODO Auto-generated method stubreturn new Binder();}@Overridepublic void onCreate() {// TODO Auto-generated method stubnew Thread() {public void run() {int i = 0;while (running) {System.out.println(i + "默认");/** * 回调方法 */if (callBack != null) {callBack.onDataChanged(i + "默认");}try {sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}};}.start();super.onCreate();System.out.println("onCreate");}public class Binder extends android.os.Binder {public MyService getMyService() {return MyService.this;}public int getRam() {Random random = new Random();return random.nextInt();}}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubreturn super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();running = false;System.out.println("onDestroy");}/** *   */private CallBack callBack = null;public void setCallBack(CallBack callBack) {this.callBack = callBack;}public CallBack getCallBack() {return callBack;}/** * 回调接口 * @author HTP * */public static interface CallBack {public void onDataChanged(String data);}}


AndroidManifest.xml

<service android:name=".MyService" >            <intent-filter>                <action android:name="com.example.test.service.MyService" />            </intent-filter>        </service>



Activity:

package com.example.test;import com.example.test.MyService.Binder;import com.example.test.MyService.CallBack;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.Handler;import android.os.IBinder;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.widget.TextView;public class ServiceTestAty extends Activity {private static final String service = "com.example.test.service.MyService";private Binder binder;private TextView tv;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.activity_service);init();}private void init() {// TODO Auto-generated method stubtv = (TextView) findViewById(R.id.tv);findViewById(R.id.bind).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent = new Intent(service);bindService(intent, ServiceConnection, Context.BIND_AUTO_CREATE);}});findViewById(R.id.unbind).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubunbindService(ServiceConnection);}});}ServiceConnection ServiceConnection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {// TODO Auto-generated method stub}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// TODO Auto-generated method stubbinder = (Binder) service;MyService myService = binder.getMyService();myService.setCallBack(new CallBack() {@Overridepublic void onDataChanged(String data) {// TODO Auto-generated method stubMessage msg = hander.obtainMessage();msg.what = 1;Bundle bundle = new Bundle();bundle.putString("data", data);msg.setData(bundle);hander.sendMessage(msg);}});}};private Handler hander = new Handler() {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubtv.setText(msg.getData().getString("data"));super.handleMessage(msg);}};}


0 0