How to create a Broacast intent to be called in onCreate? - android

How would i go about calling an broadcast intent for this class. I want to create an intent to be called inside the onCreate Method so that it can send that broadcast Receiver.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String msg = "";
if(bundle != null){
//Do Nothing
}else{
checkMessage();
}
}
}

Use sendBroadcast method. And in the Intent specify the class name of the receiver.

Related

How to pass value from BroadcastReceiver to main activity

I want to tell my MainActivity, that it is starting automatically by BroadcastReceiver when boot is completed. It seems to be possible to send over putExtra some values to the MainActivity like this:
public class StartAppAtBootReceiver extends BroadcastReceiver {
private static final String key_bootUpStart = "bootUpStart";
private static boolean bootUpStart = true;
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent activityIntent = new Intent(context, MainActivity.class);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activityIntent.putExtra(key_bootUpStart, bootUpStart);
context.startActivity(activityIntent);
}
}
}
But how can I receive that value inside my MainActivity?
On the BroadcastReceiver you send the intent to the Activity.
I modified your key to be public so that you can reuse it.
public static final String KEY_BOOTUP_START = "bootUpStart";
On the Activity you process the Intent.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
processExtraData();
}
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
setIntent(intent);
processExtraData()
}
private void processExtraData()
{
Intent intent = getIntent();
// Use the data here.
boolean value = getIntent()
.getBooleanExtra(StartAppAtBootReceiver.KEY_BOOTUP_START, false);
}
In your activity you can get the intent which has started your activiy like:
in onCreateActivity:
Intent intent = getIntent();
Than:
Object value = intent.getExtra("key_bootUpStart");

Activity cant find Bundle in Intent

I am using an IntentService (for the first time), and I intend to return the result of this service by using a Bundle. However, when I do this, the main activity does not find the Bundle, returning null. What could cause this? The string keys match!
The code bellow outputs:
I/System.out: It's null
Main Activity:
public class MainMenu extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//Some stuff here...
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(StorageHandler.TRANSACTION_DONE);
registerReceiver(broadcastReceiver, intentFilter);
Intent i = new Intent(this, StorageHandler.class);
startService(i);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extra = getIntent().getBundleExtra("bundle");
if(extra == null){
System.out.println("It's null");
}
else {
ArrayList<String> objects = (ArrayList<String>) extra.getSerializable("objects");
System.out.println(objects.get(0));
}
}
};
}
IntentService:
public class StorageHandler extends IntentService{
public static final String TRANSACTION_DONE = "xx.xxxxx.xxxxxx.TRANSACTION_DONE";
public StorageHandler() {
super("StorageHandler");
}
public void onCreate(){
super.onCreate();
}
#Override
protected void onHandleIntent(Intent intent) {
notifyFinished();
}
private void notifyFinished(){
ArrayList<String> objects = new ArrayList<String>();
objects.add("Resulting Array here");
Bundle extra = new Bundle();
extra.putSerializable("objects", objects);
Intent i = new Intent();
i.setAction(xx.xxxxx.xxxxxx.StorageHandler.TRANSACTION_DONE);
i.putExtra("bundle", extra);
StorageHandler.this.sendBroadcast(i);
}
You're attempting to retrieve the data from the wrong Intent.
Change:
Bundle extra = getIntent().getBundleExtra("bundle");
To:
Bundle extra = intent.getBundleExtra("bundle");
The Intent that contains your data is supplied as one of the parameters of the BroadcastReceiver's onReceive() method.
you are using getIntent() to retrieve the broadcasted intent. This is wrong. The intent you have to use is the former paramter of onReceive. Change
Bundle extra = getIntent().getBundleExtra("bundle");
with
Bundle extra = intent.getBundleExtra("bundle");
Simply use this in your Activity:
In onResume callback you should register registerReceiver(broadcastReceiver, intentFilter);
And in onPause callback you should unregister this receiver. In your receiver use this:
Bundle extra = intent.getBundleExtra("bundle");
In your service use this code:
Intent i = new Intent(TRANSACTION_DONE).putExtra("bundle", extra);
this.sendBroadcast(i);
More information , see This Answer
Dont forget this in your onCreate MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//All your code here
}
I say this because I dont see that code line in your method!

How to call TextToSpeech from Broadcast Receiver

I my app I'm calling a Broadcast Receiver to read incoming Text Messages and say it aloud. My Broadcast Receiver gets called properly, it reads the text message properly but when it comes to the speak() method, it just crashes. Here's my code:
This is the BroadcastReceiver:
public class DrivingModeSpeaker extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
int n;
Bundle bundle=intent.getExtras();
Object messages[]=(Object[])bundle.get("pdus");
SmsMessage smsMessage[]=new SmsMessage[messages.length];
for(n=0;n<messages.length;n++)
{
smsMessage[n]=SmsMessage.createFromPdu((byte[])messages[n]);
}
//show first message
String sms1=smsMessage[0].getMessageBody();
String from=smsMessage[0].getOriginatingAddress();
Toast toast=Toast.makeText(context,"In DrivingModeSpeaker BR",1);
toast.show();
DrivingMode.speakSMS(sms1);
}
}
And this is DrivingMode.java which contains the speak() method:
public class DrivingMode extends Activity {
private static TextToSpeech myTts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.message_m);
myTts = new TextToSpeech(this,ttsInitListener);
}
private TextToSpeech.OnInitListener ttsInitListener=new TextToSpeech.OnInitListener() {
#Override
public void onInit(int version) {
// myTts.speak(""+o, 0 ,null);
}
};
public static void speakSMS(String sms)
{
myTts.speak(sms,0,null);
}
}
I have tried out this code in a separate project, it works. But in my main project, it doesn't - could it be because of two broadcast receivers clashing or something? I dunno, I'm new to Android, please help!
Currently you are trying to call Activity method by Creating an instance of Activity which through NullPointerException if Activity is not running. so instead of calling Activity's method start Activity from BroadcastReceiver and send sms data using Intent.putExtra as :
For Example :
public void onReceive(Context context, Intent intent)
{
// Your code here....
Toast toast=Toast.makeText(context,"In DrivingModeSpeaker BR",1);
toast.show();
// start Activity here
Intent intent = new Intent(context,
DrivingMode.class);
intent.putExtra("sms", sms); //<<< put sms text
context.startActivity(intent);
}
and in DrivingMode onCreate method get sms data and call speakSMS method as :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.message_m);
Bundle extras = getIntent().getExtras();
myTts = new TextToSpeech(this,ttsInitListener);
DrivingMode.speakSMS(extras.getString("sms"));
}
also use TextToSpeech.setOnUtteranceCompletedListener for finishing Activity at the end of Speak

broadcastRecevier onreceive handling content of the message

i want to pass some information from the received message when i receive it such as the content of the message or the source number of it, and i want to put that information in a button on when a certain condition is true not oncreate, am building messaging application so i want to store my received message in "inbox" how can i do that?
Ps. my onreceive method in a class extends broadcastReceiver and my other class extends activity
thanks in advance!
here is my first class where i extends broadcastreceiver
public class Re extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String address="";
String body="";
long time = 0;
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
address= msgs[i].getOriginatingAddress();
body=msgs[i].getMessageBody().toString();
time=msgs[i].getTimestampMillis();
}
}
and here is my second class where i extends activity
public class ThirdView extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
}
}
If you want to have access to your activity from Receiver's onReceive - then you should define BroadcastReceiver as inner class of the Actvity and register it programmatically (in onStart method, and unregister in onStop);
public class ThirdView extends Activity {
private static final IntentFilter intentFilter =
new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
TextButton myButton;
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SmsMessage[] messages;
//read parse pdus data from intent and pupulate messages array
//...
//update the button
if(messages.length > 0) {
myButton.setText(messages[0].getOriginatingAddress());
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
myButton = (TextButton) findViewByiD(R.id.myButton);
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(receiver, intentFilter);
}
#Override
protected void onStop() {
unregisterReceiver(receiver);
super.onStop();
}
}

How to register BroadcastReceiver

I am new to android.I tried to register Broadcastreceiver in main class to receive sms.But when i m running logcat shows "error in receiving broadcast intent" and the application become force close.Whats the solution for this?
Here is my code:
public class Yes extends Activity {
/** Called when the activity is first created. */
private Retrieve receiver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start=(Button)findViewById(R.id.bt1);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
receiver = new Retrieve();
registerReceiver(receiver,new
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
});
}
private class Retrieve extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n<messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
smsMessage[0].getMessageBody();
}
// show first message
Toast toast = Toast.makeText(context,
"Received SMS: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast.show();
}}
I put a start button and i tried to rgister receiver within that button.I provide permission in manifest file to receive sms.i didn't write intent filter in manifest.I think the way i register receiver is completely wrong from what i want to do.help me...
In your activity outside, create a broadcast(or write it as a seperate Class):
private BroadcastReceiver smsReceiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent) {
//do your task
}
}
In onClick just regist the Receiver:
registerReceiver(smsReceiver, filter);

Categories

Resources