简体   繁体   中英

Android MainActivity and BroadcastReceiver

I have a problem when trying to reach objects from different classes. I'm on an android project an I've done a socketconnection from my MainActivity class that extends Activity. Then I've made another class called SmsReceiver that extends BroadcastReceiver so I can get messages that are sent to my phone (emulator). Now I need the SmsReceiver class to use the outputstream object from the MainActivity class but I don't know how to reach it. I cannot make a new instance of MainActivity.

Can I somehow send the outputstream object to the SmsReceiver class? I hope some of you got some tips, thanks in advance!


Ok now I've gone for the interface solution but I'm stuck again!

Here are my classes:

MainActivity:

public class MainActivity extends Activity implements MainInterface
{

try {
                            out = new PrintWriter(clientSocket.getOutputStream());
                            in = new BufferedReader(new                                InputStreamReader(clientSocket.getInputStream()));
                        } catch (IOException ex) {
                            System.err.println("Error in creating Streams:" +   ex.toString());
                            return;
                        }

public PrintWriter getOutputStream() {
        return out;
    }
}

MainInterface:

public interface MainInterface {
    public PrintWriter getOutputStream();
}

SmsReceiver:

public class SmsReceiver extends BroadcastReceiver{

    MainInterface mainInterface = new MainActivity();  ///// <------
    PrintWriter out;  //// <--------

    @Override
    public void onReceive(Context context, Intent intent) {
        mainInterface.getOutputStream(); ////// <------------
        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();

        try {
            if(bundle != null){

                final Object[] pdusObj = (Object[]) bundle.get("pdus");

                for(int i = 0; i < pdusObj.length; i++){
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                    String senderNum = phoneNumber;
                    String message = currentMessage.getDisplayMessageBody();

                    Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
                    out.println("senderNum: "+ senderNum + "; message: " + message);
                    out.flush(); /// these two lines
                }
              }
        } catch (Exception e) {
            Log.e("SmsReceiver", "Exception smsReceiver" +e);
        }
    }

}

For some reason the PrintWriter that I get through the interface is null , and the inputstream on the desktop (which is the program that should receive the message when doing out.println() ) doesn't even get the message, it's just blocked at in.readLine() . Am I instantiating the interface the wrong way or what's going on?

The logcat error print is: 09-15 14:13:55.880: E/SmsReceiver(1361): Exception smsReceiverjava.lang.NullPointerException

You must be setting an intent to BroadcastReceiver class in your MainActivity, why are you not sending the data using the intent of this BroadcastReceiver, it will be much easier than the approach I asked earlier before seeing your code.

The data you will receive in intent of broadcast receiver, please check if this solution works. But, you need to work out on a way to send a PrintWriter object through intent.

Another solution can be to use and observer and subscriber pattern, you can find multiple examples on net for same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM