簡體   English   中英

創建一個偵聽器,從 BroadcastReceiver 傳遞值

[英]Create a listener, pass value from a BroadcastReceiver

我有些懷疑如何執行一項操作。

當接到一個收入電話時,我想傳遞我的 class 的號碼,它管理與 Arduino 的藍牙連接。

發送號碼后,我想通過藍牙連接發送

我嘗試使用意圖,但也許我使用的是不推薦使用的版本。

Android Api 7.1

Brodcaster 接收器 Class

package com.jidea.glass;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class TelephonyReceiver extends BroadcastReceiver
{

    @Override
    public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
        try {
            if (intent != null && intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
                //Toast.makeText(context, "Outgoign call", 1000).show();
                String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
            } else {
                //get the phone state
                String newPhoneState = intent.hasExtra(TelephonyManager.EXTRA_STATE) ? intent.getStringExtra(TelephonyManager.EXTRA_STATE) : null;
                Bundle bundle = intent.getExtras();

                if (newPhoneState != null && newPhoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                    //read the incoming call number
                    String phoneNumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                    Log.i("PHONE RECEIVER", "Telephone is now ringing " + phoneNumber);
                    //Toast.makeText(arg0, "Tele disponivel " + phoneNumber, Toast.LENGTH_LONG).show();
                    if(phoneNumber!=null | phoneNumber.equals("")){
                               PASS HERE TO BLUETOOTH           
                    }
                }

藍牙 class

package com.jidea.glass;


import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
//import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.util.UUID;

public class CustomProcess extends AppCompatActivity
{
    String address = null;
    private ProgressDialog progress;
    BluetoothAdapter myBluetooth = null;
    BluetoothSocket btSocket = null;
    private boolean isBtConnected = false;
    //SPP UUID. Look for it
    static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    //observable


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent newint = getIntent();
        address = newint.getStringExtra(MainActivity.EXTRA_ADDRESS); //receive the address of the bluetooth device
        setContentView(R.layout.activity_custom_process);
        //msg(address);
        new ConnectBT().execute(); //Call the class to connect

    }
    public void isConnected() {//View view
        if (btSocket!=null)
        {
            try
            {
                btSocket.getOutputStream().write("Conectado".toString().getBytes());
            }
            catch (IOException e)
            {
                msg("Error");
            }
        }
    }

    public void haveCall(String Phone) {//View view
        Object aLig="Ligação \n"+Phone;
        if (btSocket!=null)
        {
            try
            {
                btSocket.getOutputStream().write(aLig.toString().getBytes());
            }
            catch (IOException e)
            {
                msg("Error");
            }
        }
    }

    private void msg(String s)
    {
        Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
    }

    private class ConnectBT extends AsyncTask<Void, Void, Void>  // UI thread
    {
        private boolean ConnectSuccess = true; //if it's here, it's almost connected

        @Override
        protected void onPreExecute()
        {
            progress = ProgressDialog.show(CustomProcess.this, "Connecting...", "Please wait!!!");  //show a progress dialog
        }

        @Override
        protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
        {
            try
            {
                if (btSocket == null || !isBtConnected)
                {
                    myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
                    BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
                    btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
                    BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                    btSocket.connect();//start connection
                }
            }
            catch (IOException e)
            {
                ConnectSuccess = false;//if the try failed, you can check the exception here
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
        {
            super.onPostExecute(result);

            if (!ConnectSuccess)
            {
                msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
                finish();
            }
            else
            {
                msg("Conectado");
                isBtConnected = true;
                isConnected();
            }
            progress.dismiss();
        }
    }


}

首先,您應該在 BroadcastReceiver 中創建一個意圖,然后使用 LocalBroadcastManager 以便能夠將該意圖發送到您想收聽的任何地方。

val intent = Intent(ACTION)
intent.putExtra("DATA KEY", DATA)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent)

不要忘記在您想收聽的地方注冊您的廣播接收器

LocalBroadcastManager.getInstance(context).registerReceiver(your broadcast receiver instance, IntentFilter(ACTION))

我解決了它,通過接口代碼完成了 Java 內部偵聽器。

 package com.jidea.glass; public interface TelephonyListener { /** * To call this method when new message received and send back * @param message Message */ void callReceived(String message); }

 public class CustomProcess extends AppCompatActivity implements MessageListener, TelephonyListener @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MessageReceiver.bindListener(this); TelephonyReceiver.bindListener(this); Intent newint = getIntent(); address = newint.getStringExtra(MainActivity.EXTRA_ADDRESS); //receive the address of the bluetooth device setContentView(R.layout.activity_custom_process); //msg(address); new ConnectBT().execute(); //Call the class to connect

 @Override public void messageReceived(String message) { Toast.makeText(this, "Nova Mensagem: " + message, Toast.LENGTH_SHORT).show(); } @Override public void callReceived(String message) { Toast.makeText(this, "Tele disponivel " + message, Toast.LENGTH_LONG).show(); haveCall(message); }
在我的 class 接收器中繼續,它擴展了 BroadcastReceiver I Donw

 public class TelephonyReceiver extends BroadcastReceiver { private static TelephonyListener mListener; @Override public void onReceive(Context arg0, Intent intent) { // TODO Auto-generated method stub } public static void bindListener(TelephonyListener listener){ mListener = listener; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM