Pass data from BroadcastReceiver class to a Android Activity

六月ゝ 毕业季﹏ 提交于 2019-11-27 21:38:15
alyon2002

Using an interface is a solution that worked for me.

In your BroadcastReceiver put the following

public interface OnSmsReceivedListener {
    public void onSmsReceived(String sender, String message);
}

then add the listener

private OnSmsReceivedListener listener = null;

then add a method to the BroadcastReceiver..

public void setOnSmsReceivedListener(Context context) {
    this.listener = (OnSmsReceivedListener) context;
}

then in your onReceive method you can do something like this...

if (listener != null) {
    listener.onSmsReceived(sender, msg);
}

in the activity that creates and registers the BroadcastReceiver start by implementing the OnSmsReceivedListener interface, then do the following

public class SomeActivity extends Activity implements OnSmsReceivedListener.....

private MissedCallActivity receiver;

in the onCreate method add

receiver = new MissedCallActivity();
receiver.setOnSmsListener(this);

then override the method used by the interface.

@Override
public void onSmsReceived(String sender, String message) {
    //Insert your text to speech code here
}

That should do the trick.

Also, don't forget to register your receiver in the onResume() method and unregister it in the onPause() method. Also, see how "from" is highlighted in blue? That means it's part of the Java syntax and cannot be used as a variable.

You can pass data using intents.

In your BroadcastReceiver, create an Intent:

Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("msgContent", msg);
i.putExtra("sender",from);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // adding this flag starts the new Activity in a new Task 
startActivity(i);

Then in the other Activity, you can get those values like :

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String messageContent = extras.getString("msgContent");
    String messageSender = extras.getString("sender");
}
Krishna Chaitanya

Use the CONTEXT and INTENT arguments in onReceive()

public class MissedCallActivity extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
            intent.putExtra("Number", Var_Number);
            intent.setClass(context, ReadContactsActivity.class);
            context.startActivity(intent);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!