broadcastRecevier onreceive handling content of the message - android

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

Related

LocalBroadcastManager not receiving broadcasts in a Activity

I am using a LocalBroadcastManager to make broadcast to my activtiy and services using APPLICATION CONTEXT , like this:
public class CommonForApp extends Application{
public void broadcastUpdateUICommand(String[] updateFlags,
String[] flagValues) {
Intent intent = new Intent(UPDATE_UI_BROADCAST);
for (int i = 0; i < updateFlags.length; i++) {
intent.putExtra(updateFlags[i], flagValues[i]);
}
mLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);
mLocalBroadcastManager.sendBroadcast(intent);
}}
Now Using a Listener in my Service, I am calling broadcastUpdateUICommand() ,like this:
public class mService extends Service {
public BuildNowPLaylistListListener buildCursorListener = new BuildNowPLaylistListListener() {
#Override
public void onServiceListReady() {
mApp.broadcastUpdateUICommand(
new String[] { CommonForApp.INIT_DRAWER},
new String[] {""});
}}}
And i am receiving the broadcast in my Activity, like this:
public class mActivity extends Activity{
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mtoast.showtext("in onreceive"); //toast to check
if (intent.hasExtra(CommonForApp.INIT_DRAWER))
initialiseDrawer();
}};
}
mApp is instance of Application.
CommonForApp is my Application Class.
But in my activity i am not receving any broadcast(the broadcast manager is initialised using application context) .
Can Anyone suggest me why i am not receiving broadcast in my activity? ..
.Thanks in advance !
in activity:
protected BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, final Intent intent) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(intent.hasExtra("type")){
// Do some action
}
}
});
}
};
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("data-loaded"));
}
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}
then you send broadcast:
public static void sendBroadcastMessageDataLoaded(Context context, String dataType){
Intent intent = new Intent("data-loaded");
intent.putExtra("type", dataType);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

LocalBroadcastManager not working as expected

In my Application I have to notify my Activity from IntentService class .
For that purpose I am using LocalBroadcastManager. But I am not receiving anything in the onReceive of my Broadcast Receiver. Here is what I have written.
In my BaseActivity I have registered my receiver.
public class BaseActivity extends FragmentActivity implements App {
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(custom-event-name));
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mMessageReceiver);
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
System.out.println("Overlay Message" +bundle.getString("message"));
}
};
}
I am sending a local broadcast from my RegisterAlarmIntentService class.
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
public RegisterAlramIntentService() {
super("AlarmService");
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Intent localIntent = new Intent(custom-event-name);
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
onHandleIntent() method is called. But nothing is received in onReceive() of my receiver.
Please Help. Thanks in advance!!
Try
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
Intent localIntent;
public RegisterAlramIntentService() {
super("AlarmService");
localIntent = new Intent(custom-event-name);
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Thread.sleep(5000); // For Testing only because it is in whole new thread (which may not wait for your reciever to setup)
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
Also in manifest :
<service android:name="com.commonsware.android.localcast.RegisterAlramIntentService"/>
See this

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

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

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

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.

Categories

Resources