android - 从广播接收器中的另一个类调用方法

标签 android bluetooth broadcastreceiver

我正在做一个由两个类组成的项目。第一个,MainActivity.java,处理通过蓝牙连接发送单个字符。第二个是 SmsReceiver.java,是一个用于检测传入短信的广播接收器。当 SmsReceiver.java 检测到传入消息时,它应该调用蓝牙类中的方法 turnLedOn。

我已经测试了它们,它们都有效。然后我尝试通过在广播接收器的 onReceive 方法中调用 MainActivity.turnLedOn(context); 来连接它们,但它没有用。

有谁知道为什么以及应该采取什么措施来解决这个问题?下面是整个项目的代码。

提前谢谢你。

MainActivity.java

package com.example.bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

    //You first have to connect with your android phone to the arduino bt module.
    BluetoothAdapter mBluetoothAdapter = null;
    ConnectThread  mConnectThread = null;
    BluetoothDevice mDevice = null;
    public static ConnectedThread mConnectedThread = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mConnectedThread.write("1".getBytes());
            }
        });

        final Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mConnectedThread.write("0".getBytes());
            }
        });

       BluetoothDevice mDevice = null; 
       //Check if phone supports bluetooth 
       mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
        // Device does not support Bluetooth
        }
        Toast.makeText(this, "BT supported", Toast.LENGTH_SHORT).show();
        Log.e("BLUETOOTH", "BT supported");

        // Check if bluetooth is enabled. If not, enable it.
        if (!mBluetoothAdapter.isEnabled()) {
            Toast.makeText(this, "BT disabled", Toast.LENGTH_SHORT).show();

            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
        Toast.makeText(this, "BT enabled", Toast.LENGTH_SHORT).show();
        Log.e("BLUETOOTH", "BT enabled");

        // Chech which device we connected with, at the beginning
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            Toast.makeText(this, "Paired with a BT device", Toast.LENGTH_SHORT).show();
            Log.e("BLUETOOTH", "paired with a BT device");

            for (BluetoothDevice device : pairedDevices) {
                Toast.makeText(this, device.getName() + " " + device.getAddress(), Toast.LENGTH_SHORT).show();
                mDevice = device;
            }
        }

        // Source 7 - Creating the connection thread
        mConnectThread = new ConnectThread(mDevice);
        mConnectThread.start();

    }


    public static void turnLedOn(Context context){
        mConnectedThread.write("1".getBytes());
   }

    public static void turnLedOff(Context context){
        mConnectedThread.write("0".getBytes());
   }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //Thread which creates a connection between arduino and phone
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
        private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

        public ConnectThread(BluetoothDevice device) {
            BluetoothSocket tmp = null;
            mmDevice = device;

            try {
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) { }
                mmSocket = tmp;
        }

        public void run() {
            mBluetoothAdapter.cancelDiscovery();
            try {
                mmSocket.connect();
            } catch (IOException connectException) {

            try {
                mmSocket.close();
            } catch (IOException closeException) { }
                return;
            }

            //Source 10 - create the data transfer thread
            //Manage connection 
            mConnectedThread = new ConnectedThread(mmSocket);
            mConnectedThread.start();
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }  
    // end of connection thread

    //Thread for sending and receiving messages
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
            }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            int begin = 0;
            int bytes = 0;
            while (true) {
                try {
                    bytes += mmInStream.read(buffer, bytes, buffer.length
                            - bytes);
                    for (int i = begin; i < bytes; i++) {
                        if (buffer[i] == "#".getBytes()[0]) {
                            mHandler.obtainMessage(1, begin, i, buffer)
                                    .sendToTarget();
                            begin = i + 1;
                            if (i == bytes - 1) {
                                bytes = 0;
                                begin = 0;
                            }
                        }
                    }

                } catch (IOException e) {
                    break;
                }
            }
        }

        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
            }
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
            }
        }
    }
    //End of thread for sending and receiving

    //Source 9 - handler for sending
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            byte[] writeBuf = (byte[]) msg.obj;
            int begin = (int) msg.arg1;
            int end = (int) msg.arg2;

            switch (msg.what) {
            case 1:
                String writeMessage = new String(writeBuf);
                writeMessage = writeMessage.substring(begin, end);
                break;
            }
        }
    };

}

SmsReceiver.java

package com.example.bluetooth;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String messageReceived = "";            
        if (bundle != null)
        {
            //---retrieve the SMS message received---
           Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++)

            {
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
                messageReceived += msgs[i].getMessageBody().toString();
                messageReceived += "\n";        
            }

            //---display the new SMS message---
            Toast.makeText(context, messageReceived, Toast.LENGTH_SHORT).show();
            MainActivity.turnLedOn(context);

            // Get the Sender Phone Number
            String senderPhoneNumber=msgs[0].getOriginatingAddress ();   

       }                         
    }
}

MainActivity 布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="34dp"
        android:text="On" />

    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="68dp"
        android:text="Off" />

</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bluetooth"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />



    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <receiver android:name=".SmsReceiver"> 
            <intent-filter> 
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" /> 
            </intent-filter> 
        </receiver>

        <activity
            android:name="com.example.bluetooth.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

   <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

</manifest>

编辑按照@donison24x7 的建议在 list 中注册广播接收器。

Edit2:对此感到抱歉。还在 list 中添加了 RECEIVE_SMS 权限。现在可以使用了。

最佳答案

您还没有在 list 中注册广播接收器“SmsReceiver.java”。 像这样注册......

        <receiver 
              android:name=".SmsReceiver" >
            <intent-filter>
                <action android:name="your.Action.name" /> 
            </intent-filter>
        </receiver>

关于android - 从广播接收器中的另一个类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28108822/

相关文章:

java - 来自 XML 的 MapView 的 Android InflateException

ios - ReadRSSI 不调用委托(delegate)方法

android - 如何通过蓝牙使用安卓应用程序连接到树莓派

android - BroadcastReceiver Intent 不接收额外内容

android - 来自广播接收器的 Toast 消息

android - 我需要将广播与警报管理器一起使用吗?

android - uiController.loopMainThreadForAtLeast 与 Thread.sleep 有何不同?

java - 谷歌 GSON : How to use @Since annotation for e. g。版本 "1.2.1"? (无效双)

javascript - 如何从 WebView 中获取 Cookie?

ios - OSX 和 iOS 之间的蓝牙通信