سؤال

I just cannot get this code to work. I looked on stackoverflow and found some articles and tried all the methods, but no luck. So I basically have 1 activity and 1 BroadcastReceiver class. In the BroadcastReceiver, I have it waiting for a text message to come in and then grab the data and send it off to the front facing UI activity and update the message on the UI to the data that was send from the BroadcastReceiver. So Essentially, if a text came in from "1234567890" with a message text of "hello", the BroadcastReceiver would grab both that data and send it off to the Activity and then the Activity receives it and updates the message TextView to "From: 1234567890, Msg: hello". And this message TextView would be updated everytime a call to onReceive() in BroadcastReceiver is made. Here is what I have so far:

BroadcastRecieverNewSms:

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class BroadcastRecieverNewSms extends Activity {

TextView message;
IncomingSms myReceiver = null;
Boolean myReceiverIsRegistered = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    message = (TextView) findViewById(R.id.message);
    myReceiver = new IncomingSms();

}

@Override
protected void onResume() {
    super.onResume();
    if (!myReceiverIsRegistered) {
        registerReceiver(myReceiver, new IntentFilter("org.rivercityrocketry.smsreadergprs.SENT_NUM"));
        myReceiverIsRegistered = true;
        String senderNum = myReceiver.getResultData();
        message.setText(senderNum);
        Toast.makeText(getBaseContext(), "senderNum: "+ senderNum, Toast.LENGTH_LONG).show();
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (myReceiverIsRegistered) {
        unregisterReceiver(myReceiver);
        myReceiverIsRegistered = false;
    }
}

/*protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  //if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
    //if (data.hasExtra("returnKey1")) {
      //Toast.makeText(this, data.getExtras().getString("returnKey1"), Toast.LENGTH_SHORT).show();
      handleSendText(data);
    //}
  //}
} */

void handleSendText(Intent intent) {
    String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
    if (sharedText != null) {
        message.setText(sharedText);
    }
}


@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;
}

public void setMessage(String m) {
    message.setText(m);
}

}

IncomingSms:

import java.io.File;
import java.io.FileOutputStream;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.sax.StartElementListener;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class IncomingSms extends BroadcastReceiver {

// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();

public void onReceive(Context context, Intent intent) {

    // 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();

                    Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, Toast.LENGTH_LONG).show();
                    Intent sendIntent = new Intent("org.rivercityrocketry.smsreadergprs.SENT_NUM");
                    sendIntent.putExtra("SENDNUM", senderNum);
                    context.sendBroadcast(sendIntent);    
            } 
          } // if bundle is null

    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" + e);
    }
}

}

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.rivercityrocketry.smsreadergprs"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="org.rivercityrocketry.smsreadergprs.BroadcastRecieverNewSms"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <!-- <category android:name="android.intent.category.DEFAULT" /> 
                <data android:mimeType="text/plain" />     -->   
            </intent-filter>
        </activity>

        <receiver android:name="org.rivercityrocketry.smsreadergprs.IncomingSms" >
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>
    </application>

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

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

</manifest>

activity_main.xml:

<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=".BroadcastRecieverNewSms" >

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

</RelativeLayout>

Any help is greatly appreciated! I've been working on this for a long time now and just can't seem to understand BroadcastReceivers. Thanks!

هل كانت مفيدة؟

المحلول

Override onRecieve within BroadcastRecieverNewSms :

 @Override
protected void onResume() {
    myReceiver = new IncomingSms(){ 
        public void onReceive(Context context, Intent intent) {
        //get data from intent and populate textview
        }
    };
    IntentFilter filter  = new IntentFilter("org.rivercityrocketry.smsreadergprs.SENT_NUM");
    RegisterReceiver(myReceiver,filter);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top