• 08-Android 中 Service 通信


    启动service并传输数据:

    main_activity.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        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"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
    
        <EditText
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/etData"
            android:text="默认信息"
            />
    
        <Button
            android:id="@+id/btnStartService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="启动服务" />
    
        <Button
            android:id="@+id/btnStopService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="停止服务" />
    
    </LinearLayout>

    MyService.java:

    package com.imooc.connectservice;
    
    import android.app.Service;
    import android.content.Intent;
    import android.os.IBinder;
    
    public class MyService extends Service {
        private boolean running = false;
        private String data = "这是默认信息";
    
        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();
            running = true;
            new Thread(){
                @Override
                public void run(){
                    super.run();
    
                    while (running){
                        System.out.println(data);
                        try {
                            sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
                    }
    
                }
            }.start();
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
    
            running = false;
        }
    }

    MainActivity.java:

    package com.imooc.connectservice;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.EditText;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        private EditText etData;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            etData = (EditText) findViewById(R.id.etData);
    
            findViewById(R.id.btnStartService).setOnClickListener(this);
            findViewById(R.id.btnStopService).setOnClickListener(this);
    
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btnStartService:
                    Intent i = new Intent(this,MyService.class);
                    i.putExtra("data",etData.getText().toString());
                    startService(i);
                    break;
                case R.id.btnStopService:
                    stopService(new Intent(this,MyService.class));
    
            }
        }
    }


     绑定Service进行通信-上之执行服务的内部代码:

    activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
        <EditText
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:text="默认信息"
            android:id="@+id/etData"
            />
    
        <Button
            android:id="@+id/btnStartService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="启动服务" />
    
        <Button
            android:id="@+id/btnStopService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="停止服务" />
    
        <Button
            android:id="@+id/btnBindService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="绑定服务" />
    
        <Button
            android:id="@+id/btnUnBindService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="解除绑定服务" />
    
        <Button
            android:id="@+id/btnSyncData"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="同步数据" />
    
    
    </LinearLayout>

    MyService.java:

    package com.example.connectservice;
    
    import android.app.Service;
    import android.content.Intent;
    import android.os.IBinder;
    
    public class MyService extends Service {
        private boolean running = false;
        private String data = "这是默认信息";
    
        public MyService() {
        }
    
        @Override
        public IBinder onBind(Intent intent){
            return new Binder();
        }
    
        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();
    
            running = true;
            new Thread(){
                @Override
                public void run() {
                    super.run();
    
                    while (running){
    
                        System.out.println(data);
    
                        try {
                            sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
    
    
            running = false;
        }
    }

    MainActivity.java:

    package com.example.connectservice;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    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.View;
    import android.widget.EditText;
    import android.widget.TextView;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {
    
        private EditText etData;
        private MyService.Binder binder = null;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            etData = (EditText) findViewById(R.id.etData);
    
            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 void onClick(View view) {
                switch (view.getId()){
    
                    case R.id.btnStartService:
                    Intent i = new Intent(this,MyService.class);
                    i.putExtra("data",etData.getText().toString());
                        startService(i);
                    break;
                    case R.id.btnStopService:
                        stopService(new Intent(this,MyService.class));
                    break;
                    case R.id.btnBindService:
                        bindService(new Intent(this,MyService.class),this, Context.BIND_AUTO_CREATE);
                        break;
                    case R.id.btnUnBindService:
                        unbindService(this);
                        break;
    
                    case R.id.btnSyncData:
                        if (binder!= null) {
                            binder.setData(etData.getText().toString());
    
                    }
                        break;
    
            }
        }
    
        @Override
        public void onServiceConnected(ComponentName Name, IBinder service) {
            binder = (MyService.Binder) service;
        }
    
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
    
        }
    }

    绑定service进行通信-下之增添服务的内部状态:

      若程序内部代码发生改变如何通知外界代码

    activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvOut"
            />
    
        <EditText
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:text="默认信息"
            android:id="@+id/etData"
            />
    
        <Button
            android:id="@+id/btnStartService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="启动服务" />
    
        <Button
            android:id="@+id/btnStopService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="停止服务" />
    
        <Button
            android:id="@+id/btnBindService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="绑定服务" />
    
        <Button
            android:id="@+id/btnUnBindService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="解除绑定服务" />
    
        <Button
            android:id="@+id/btnSyncData"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="同步数据" />
    
    
    </LinearLayout>

    MyService.java:

    package com.example.connectservice;
    
    import android.app.Service;
    import android.content.Intent;
    import android.os.IBinder;
    
    public class MyService extends Service {
        private boolean running = false;
        private String data = "这是默认信息";
    
        public MyService() {
        }
    
        @Override
        public IBinder onBind(Intent intent){
            return new Binder();
        }
    
        public class Binder extends android.os.Binder{
    
            public void setData(String data){
                MyService.this.data = data;
            }
        }
    
            //3
            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();
    
            running = true;
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    //3
                    int i = 0;
    
                    while (running){
                    //3
                        i++;
                        String str = i+":"+data;
                        System.out.println(str);
    
                        if (callback!=null){
                            callback.onDataChange(str);
                        }
    
    
    
                        try {
                            sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
    
    
            running = false;
        }
    
        //3
        private Callback callback = null;
    
        public void setCallback(Callback callback) {
            this.callback = callback;
        }
    
        public Callback getCallback() {
            return callback;
        }
    
        //3
        public static interface Callback{
            void onDataChange(String data);
        }
    
    
    }

    MainActivity.java:

    package com.example.connectservice;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    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.widget.EditText;
    import android.widget.TextView;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {
    
        private EditText etData;
        private MyService.Binder binder = null;
        //3
        private TextView tvOut;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            etData = (EditText) findViewById(R.id.etData);
            //3
            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 void onClick(View view) {
            switch (view.getId()){
    
                case R.id.btnStartService:
                    Intent i = new Intent(this,MyService.class);
                    i.putExtra("data",etData.getText().toString());
                    startService(i);
                    break;
                case R.id.btnStopService:
                    stopService(new Intent(this,MyService.class));
                    break;
                case R.id.btnBindService:
                    bindService(new Intent(this,MyService.class),this, Context.BIND_AUTO_CREATE);
                    break;
                case R.id.btnUnBindService:
                    unbindService(this);
                    break;
    
                case R.id.btnSyncData:
                    if (binder!= null) {
                        binder.setData(etData.getText().toString());
    
                    }
                    break;
    
            }
        }
    
        @Override
        public void onServiceConnected(ComponentName Name, IBinder service) {
            binder = (MyService.Binder) service;
            //3
            binder.getService().setCallback(new MyService.Callback() {
                @Override
                public void onDataChange(String data) {
                    Message msg = new Message();
                    Bundle b = new Bundle();
                    b.putString("data",data);
                    msg.setData(b);
                    handler.sendMessage(msg);
    
                }
            });
        }
    
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
    
        }
    
        //3
        private Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                tvOut.setText(msg.getData().getString("data"));
    
            }
        };
    }
  • 相关阅读:
    Postman模拟后端服务(mock server)
    Fiddler常用的几个功能
    Postman常用的几个功能
    Postman常用功能详解,常用请求方法
    sql小技巧
    postman接口数据关联
    postman批量发送多个请求
    sql去重查询语句
    pytho接口自动化-session
    charles抓包使用教程
  • 原文地址:https://www.cnblogs.com/juham/p/15212727.html
Copyright © 2020-2023  润新知