如何在 Activity 之间传输变量?

问题描述 投票:0回答:1

我有一个通过蓝牙传输值的代码 里面有两个活动。我需要确保 bluetoothController 变量传递给另一个活动,并且我还可以从第二个活动传输值。

首次活动

package com.example.bluetoothmodule2

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import androidx.appcompat.content.res.AppCompatResources
import androidx.navigation.fragment.findNavController
import com.example.bluetoothmodule2.databinding.FragmentMainBinding
import com.example.bt_def.BluetoothConstants
import com.example.bt_def.bluetooth.BluetoothController

class MainFragment : Fragment(), BluetoothController.Listener{
    private lateinit var binding: FragmentMainBinding
    private lateinit var bluetoothController: BluetoothController
    private lateinit var btAdapter: BluetoothAdapter
    private var rm = 0   // руль
    private var gm = 0   // газ
    private var dm= 0   // коробка передач
    private var hm = 0   // сигнал

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        binding = FragmentMainBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initBtAdapter()
        val pref = activity?.getSharedPreferences(
            BluetoothConstants.PREFERENCES, Context.MODE_PRIVATE
        )
        val mac = pref?.getString(BluetoothConstants.MAC, "")
        bluetoothController = BluetoothController(btAdapter)
        binding.bList.setOnClickListener {
            findNavController().navigate(R.id.action_FirstFragment_to_deviceListFragment)
        }
       binding.Villas.setOnClickListener {
           findNavController().navigate(R.id.action_mainFragment_to_villasFragment)
    }
        binding.Starter.setOnClickListener {
            findNavController().navigate(R.id.action_mainFragment_to_startFragment)
        }
        binding.bConnect.setOnClickListener {
            bluetoothController.connect(mac ?: "", this)
        }


        binding.RSend.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { // Слайдер для руля
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                rm = progress
                binding.textR.text = "Руль: $rm"
                bluetoothController.sendMessage("rm=${rm};")
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }
        })

        binding.GSend.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener{ //Слайдер для газа
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                gm = progress
                binding.textG.text = "Газ: $gm"
                bluetoothController.sendMessage("gm=${gm};")
            }


            override fun onStartTrackingTouch(seekBar: SeekBar?) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }

        })


        binding.VSend.setOnClickListener {
            dm = 1
            bluetoothController.sendMessage("dm=${dm};")
        }
        binding.NSend.setOnClickListener {
            dm = 0
            bluetoothController.sendMessage("dm=${dm};")
        }
        binding.BSend.setOnClickListener {
            dm = 2
            bluetoothController.sendMessage("dm=${dm};")
        }
        binding.SSend.setOnClickListener {
            hm = 1
            bluetoothController.sendMessage("hm=${hm};")
        }
        binding.R0.setOnClickListener {
            binding.RSend.progress = 0
            bluetoothController.sendMessage("rm=${rm};")
        }
    }




    private fun initBtAdapter() {
        val bManager = activity?.getSystemService(Context.BLUETOOTH_SERVICE) as
                BluetoothManager
        btAdapter = bManager.adapter
    }

    override fun onReceive(message: String) {
        activity?.runOnUiThread {
            when (message) {
                BluetoothController.BLUETOOTH_CONNECTED -> {
                    binding.bConnect.backgroundTintList = AppCompatResources
                        .getColorStateList(requireContext(), R.color.red)
                    binding.bConnect.text = "Disconnect"
                }

                BluetoothController.BLUETOOTH_NO_CONNECTED -> {
                    binding.bConnect.backgroundTintList = AppCompatResources
                        .getColorStateList(requireContext(), R.color.green)
                    binding.bConnect.text = "Connect"
                }

                else -> {
                    binding.tvStatus.text = message
                }
            }
        }
    }
}

第二个活动

package com.example.bluetoothmodule2

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import com.example.bluetoothmodule2.databinding.FragmentVillasBinding
import com.example.bt_def.BluetoothConstants
import com.example.bt_def.bluetooth.BluetoothController

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

class VillasFragment : Fragment(), BluetoothController.Listener{
    private lateinit var binding: FragmentVillasBinding
    private lateinit var bluetoothController: BluetoothController
    private lateinit var btAdapter: BluetoothAdapter
    private var param1: String? = null
    private var param2: String? = null
    private var vt = 0 // тормоз вилы
    private var gt = 0 // газ вилы
    private var ut = 0 // Вверх/Вниз вилы
    private var ft = 0 // От себя/К себе

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        binding = FragmentVillasBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initBtAdapter()
        val pref = activity?.getSharedPreferences(
            BluetoothConstants.PREFERENCES, Context.MODE_PRIVATE
        )
        val mac = pref?.getString(BluetoothConstants.MAC, "")
        bluetoothController = BluetoothController(btAdapter)
        bluetoothController.connect(mac ?: "", this)


        binding.TVillas.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { // Слайдер для руля
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                vt = progress
                binding.Ttext.text = "Тормоз: $vt"
                bluetoothController.sendMessage("vt=${vt};")
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }
        })

        binding.GVillas.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { // Слайдер для руля
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                gt = progress
                binding.Gtext.text = "Газ: $gt"
                bluetoothController.sendMessage("gt=${gt};")
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }
        })

        binding.UDVillas.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { // Слайдер для руля
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                 ut = progress
                binding.UpDownText.text = "Вверх/Вниз: $ut"
                bluetoothController.sendMessage("ut=${ut};")
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }
        })

        binding.FTVillas.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { // Слайдер для руля
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                ft = progress
                binding.FromMtoMText.text = "От себя/К себе: $ft"
                bluetoothController.sendMessage("ft=${ft};")
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }
        })
    }

    companion object {

        fun newInstance(param1: String, param2: String) =
            VillasFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }

    private fun initBtAdapter() {
        val bManager = activity?.getSystemService(Context.BLUETOOTH_SERVICE) as
                BluetoothManager
        btAdapter = bManager.adapter
    }

    override fun onReceive(message: String) {
    }
}

我尝试执行与第一个活动相同的操作,但是当切换到第二个活动时,蓝牙连接中断了

kotlin bluetooth transmission
1个回答
0
投票
val intent = Intent(activity?, activity2::class.java)
intent.putExtra("name your var in one word",value you want to transfer)
startActivity(intent) 
© www.soinside.com 2019 - 2024. All rights reserved.