android Service

本文介绍了一个自定义的Android服务(MyService)与活动组件(ServiceActivity)之间的交互方式,通过Binder机制实现服务状态的绑定与解绑,并传递数据更新通知。文章详细展示了如何在服务中设置回调接口来通知客户端数据变化,并在活动中实现该接口以更新UI。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Myservice
package com.example.halfopen.mytools;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {
    private String s = "默认信息";
    private boolean running = false;
    private SetBinder binder = new SetBinder();
    private Callback callback = null;


    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.running = false;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        running = true;

        new Thread(){
            @Override
            public void run() {
                super.run();
                int i = 0;
                while(running){
                    i++;
                    String str = i+s;
                    System.out.println(str);

                    if(callback !=null){
                        callback.onDataChange(str);
                    }
                    try {
                        sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        }.start();


    }

    public Callback getCallback() {
        return callback;
    }

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

    class SetBinder extends Binder{

        public void setRunning(boolean flag){
            running = flag;
        }

        public MyService getService(){
            return MyService.this;
        }
    }

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

Activity

package com.example.halfopen.mytools;

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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


public class ServiceActivity extends Activity implements View.OnClickListener, ServiceConnection {

    MyService.SetBinder binder;
    TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);

        text = (TextView) findViewById(R.id.text);

        findViewById(R.id.btn_startService).setOnClickListener(this);
        findViewById(R.id.btn_stopService).setOnClickListener(this);
        findViewById(R.id.btn_bindService).setOnClickListener(this);
        findViewById(R.id.btn_unbindService).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_, 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 v) {
        Intent it =new Intent(ServiceActivity.this, MyService.class);
        switch (v.getId()){
            case R.id.btn_startService:
                Toast.makeText(ServiceActivity.this, "启动服务", Toast.LENGTH_SHORT).show();
                startService(it);
                break;
            case R.id.btn_stopService:
                Toast.makeText(ServiceActivity.this, "停止服务", Toast.LENGTH_SHORT).show();
                stopService(it);
                break;
            case R.id.btn_bindService:
                Toast.makeText(ServiceActivity.this, "绑定服务", Toast.LENGTH_SHORT).show();
                bindService(it, this, Context.BIND_AUTO_CREATE);
                break;
            case R.id.btn_unbindService:
                Toast.makeText(ServiceActivity.this, "解除绑定", Toast.LENGTH_SHORT).show();
                try{
                    unbindService(this);
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Toast.makeText(ServiceActivity.this, "服务绑定成功", Toast.LENGTH_SHORT).show();
        binder = (MyService.SetBinder) service;
        binder.getService().setCallback(new MyService.Callback() {
            @Override
            public void onDataChange(String str) {
                //获取myService内部的数据
                Message msg = new Message();
                Bundle b = new Bundle();
                b.putString("data", str);
                msg.setData(b);
                handler.sendMessage(msg);
            }
        });


    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Toast.makeText(ServiceActivity.this, "服务结束", Toast.LENGTH_SHORT).show();
    }

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值