send data from a broadcast to an activity . how to do send? - android

how to send data from a broadcatReceiver to an activity in android as saying catch the received SMS and send the SMS (is the data) to the activity its my first time that i work with broadcatReceiver so can anyone help me i will appreciate any help.
i read several tutorials about the data transferring that have some steps :
create a class that extends activity
create a class that extends broadcastReceiver
but i did not know how is the communication between these 2 classes.

I would do something like that:
public class YourActivity extends Activity
{
private Handler handler = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.id.main_layout);
this.handler = new Handler() {
#Override
public void handleMessage(Message msg)
{
SmsMessage sms = (SmsMessage) msg.obj;
String senderNumber = sms.getOriginatingAddress();
}
};
// Register a new receiver that will trigger on SMS_RECEIVED event
IntentFiler filer = new IntentFilert("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(mSmsReceiver, filter);
}
#Override
protected void onDestroy()
{
super.onDestroy();
// Unregister the receiver
unregisterReceiver(mSmsReceiver);
}
private mSmsReceiver = new BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
if (bundle == null || bundle.containsKey("pdus") return;
// Decode the message
SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdus[0]);
// Notify the activity with the message
Message msg = new Message;
msg.obj = sms;
YourActivity.this.handler.sendMessage(msg);
}
};
}

The receiver and the Activity are separate entities and do not usually interact directly. Imagine the following scenario: you have a receiver getting lots of SMS messages, and every time you get one, you launch an Activity to show the message received. Wouldn't this be very annoying to the user?
I'd says that you can interact with the user by creating a Notification and if the user clicks on it, then you open the Activity you want to show the details.
As how to pass the data to the Activity (hopefully using a notification first), given that SMS messages are short in nature you can just put the data in the Intent.
How to set a Notification to launch an Activity: see Open application after clicking on Notification

Related

How to send data from BroadcastReceiver to Fragment in android

I am trying to make an chatting app.I have a SlidingDrawer Activity and it has many fragments and among which ChatFragment is one.Now when i am sending message to my friend , i have a Chatting Window and if any message comes from GCM service and i am in ChatFragment then this message will go to that Fragment and update the listview as i want to update the chatWindow when any message comes while chatting Now I tried to do like below.
GcmIntentService :
public class GcmIntentService extends IntentService {
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (extras != null && !extras.isEmpty()) { // has effect of unparcelling Bundle
// Since we're not using two way messaging, this is all we really to check for
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
Logger.getLogger("GCM_RECEIVED").log(Level.INFO, extras.toString());
showToast(extras.getString("message"));
Intent sendData = new Intent("chatupdater");
sendData.putExtra("msg", extras.getString("message"));
LocalBroadcastManager.getInstance(this).sendBroadcast(sendData);
Log.i("chat","i am in GCMIntentService");
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
Here i am starting a broadcastreceiver in onHandleIntent().
ChatBroadCastReceiver:
public class ChatBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("chat","I am in ChatBroadCastReceiver");
String msg = intent.getStringExtra("msg");
Log.i("chat",msg);
//Intent data = new Intent("chatupdater");
//Intent data = new Intent("chatupdater");
//data.putExtra("key","data");
//data.putInt("fragmentno",1); // Pass the unique id of fragment we talked abt earlier
//context.sendBroadcast(intent);
}
}
This is my ChatBroadCastReceiver class and if any message comes it successfully receives at the onReceive() method.Now i want to send this message to the Fragment.What i tried , i registered the Fragment with it and tried to get the same data at the onReceive() of ChatFragment.But it didn't call.I tried to see by logging.
public class ChatFragment extends Fragment {
//ChatBroadCastReceiver mReceiver;
private EditText et_chat;
Bundle mailData;
String caller_mail;
private ListView chatListview;
private ChatWindowAdapter chatWindowAdapter;
private List<ChatSession>PreviousChatSession;
private List<ChatInfo> chatListItems;
Button chat_send;
public ChatFragment() {
}
public BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("chat","I am in BroadCastReceiver");
String msg = intent.getStringExtra("msg");
Toast.makeText(getActivity(),msg,Toast.LENGTH_LONG).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReceiver = new ChatBroadCastReceiver();
//getActivity().registerReceiver(new ChatBroadCastReceiver(),new IntentFilter("chatupdater"));
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(new ChatBroadCastReceiver(),new IntentFilter("chatupdater"));
Log.i("chat", "I am in onCreate");
}
Now how can i get the message which i got in the Broadcastreceiver to the onReceive() of ChatFragment??
Try this
Create an interface which will have a method like this.
public interface DemoListener {
public void receiveMessage(String message);
}
Now implement this in your fragment and register the listener in BroadcastReceiver, now as soon as your broadcast receiver receives any message it will be available to your fragment via this Listener.Hope this helps.
To Register your Broadcast You are using:
mReceiver = new ChatBroadCastReceiver();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver ,new IntentFilter("chatupdater"));
So you will Only receive Broadcast on ChatBroadCastReceiver class. Because mReceiver is a Instance of ChatBroadCastReceiver class.
Now to Receive broadcast Message on anonymous class that you have created in your ChatFragment you need to register that like below code. Where mReceiver is a Instance of anonymous BroadcastReceiver class that you have implemented in your ChatFragment class.
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver ,new IntentFilter("chatupdater"))
To Receive Broadcast Message Both on ChatFragment and ChatBroadCastReceiver you need to register broadcast receiver twice.
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver ,new IntentFilter("chatupdater"))
ChatBroadCastReceiver mChatBroadCastReceiver = new ChatBroadCastReceiver();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mChatBroadCastReceiver ,new IntentFilter("chatupdater"))
Hope this answer will help you to understand your problem.

How to read sms using Service

I am receiving sms using Broadcast Receiver.It is working fine. Now I want to read sms from inbox using service, (which is received by broadcast receiver).
I want to retreive sms from inbox using SERVICE. SMS retreival must be happen in background not in main thread.No any Activity should be used.
//Broadcast receiver to receive sms and starting a service via intent
public class SMSReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] message = null;
String str = "";
if(bundle != null){
Object[] pdus = (Object[])bundle.get("pdus");
message = new SmsMessage[pdus.length];
for(int i = 0; i<message.length; i++){
message[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "New SMS from cloudy contacts " + message[i].getOriginatingAddress();
}
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
Intent intent1 = new Intent(context,MyService.class);
context.startService(intent1);
}
}
}
Servie
public class MyService extends Service{
ReadSMS readSMS;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public void onCreate(Bundle savedInstanceState){
Log.d("Service","inside onCreate of service");
}
public void onDestroy(){
Log.d("Service", "destroyed");
}
public void onStart(){
Log.d("Service","starting service to read sms from inbox");
Toast.makeText(this,"Reading sms from inbox",Toast.LENGTH_LONG).show();
readSMS = new ReadSMS();
ArrayList list = readSMS.readSms("inbox");
}
public class ReadSMS{
public ArrayList readSms(String inbox){
ArrayList sms = new ArrayList();
Uri uri = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uri, new String[]{"_id","address","date","body"},null,null,null);
cursor.moveToLast();
String address = cursor.getString(1);
String body = cursor.getString(3);
sms.add(address+" "+body);
return sms;
}
}
}
The Messages in the inbox wouldn't be received by a broadcast receiver since it's not a broadcast. You will have to read the native database on the device.
Take a look here
EDIT:
First of all, doing something from a Service doesn't automatically spawn a background thread. The service will run on the main thread.
Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.
Then you can of course spawn a thread yourself, or use an IntentService. But start by reading here.

Passing Data from Broadcast Receiver to another Activity

Hi I've been having an issue with Broadcast Receivers and passing information to another activity. I'm trying to create an application that will capture incoming SMS messages, look for a website in the text, then pop up an Alert Dialog box asking if the user wants to go to the website.
public class TextReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent)
{
// .. other code that
// sets received SMS into message
Toast toast = Toast.makeText(context,
"Received Text: " + message.getMessageBody(), Toast.LENGTH_LONG);
toast.show();
}
So that code works fine, receive a text it pops up a toast with the message. The toast is useless but it shows the receiver works. But I want to communicate with an activity to show an Alert Dialog and start up a webView. I already programmed the code that will take a string search for the website and open the webView. Is it possible to get the string from the broadcast receiver and do something like this?:
public class ReceiveText extends Activity{
public void onCreate(Bundle savedInstanceState) {
// Somehow pass the string from the receiver into this activity,
//stored in variable messages
findOpen(messages);
// is that possible?
}
public class findOpen(string messages){
// do stuff ... open alert...open site if OK
}
So basically I just want to pass a string from a Broadcast Receiver to another activity that will use that string. The rest of the code is basically in place all I need is that string... I'm new to this and Java and any help would be much appreciated. Thanks
Instantiate a BroadcastReceiver in the activity you want to get your data to, for example:
private BroadcastReceiver mServiceReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent)
{
//Extract your data - better to use constants...
String IncomingSms=intent.getStringExtra("incomingSms");//
String phoneNumber=intent.getStringExtra("incomingPhoneNumber");
}
};
Unregister your receiver on onPause():
#Override
protected void onPause() {
super.onPause();
try {
if(mServiceReceiver != null){
unregisterReceiver(mServiceReceiver);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Register it on onResume():
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.SmsReceiver");
registerReceiver(mServiceReceiver , filter);
}
Broadcast your data from the service via an Intent, for Example:
Intent i = new Intent("android.intent.action.SmsReceiver").putExtra("incomingSms", message);
i.putExtra("incomingPhoneNumber", phoneNumber);
context.sendBroadcast(i);
and that's it! goodLuck!
If you have your activity named ReceiveText, then in your BroadcastReceiver, you should do the following:
Intent i = new Intent(context, ReceiveText.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("message", message.getMessageBody());
context.startActivity(i);
Then, in your activity, you will need to getExtra as so:
Intent intent = getIntent();
String message = intent.getStringExtra("message");
And then you will use message as you need.
If you simply want the ReceiveText activity to show the message as a dialog, declare <activity android:theme="#android:style/Theme.Dialog" /> in your manifest for ReceiveText and then set the message to a textview in the activity.
EDIT: This restarts your activity. this answer is likely a better solution for most people.
We can send the data from onReceive to another activity using LocalBroadcastManager.
It means you are again broadcasting the data using the context
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Broadcast", "wifi ConnectivityReceiver");
Bundle extras = intent.getExtras();
Intent intent = new Intent("broadCastName");
// Data you need to pass to another activity
intent .putExtra("message", extras.getString(Config.MESSAGE_KEY));
context.sendBroadcast(intent );
}

How to send data to a running activity from Broadcast Receiver,

I am able to receive C2DM message fine but I want to send the data to a running activity, i.e when the activity is running, if the receiver receives C2DM message it is to send the data to the running activity. The code of receiver is (no bugs in the code):
public class C2dmreceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.w("C2DM", "Message Receiver called");
if ("com.google.android.c2dm.intent.RECEIVE".equals(action))
{
final String payload = intent.getStringExtra("key1");
Log.d("C2DM", "message = " + payload );
}
}}
I have tried like this inside the activity in an attempt to register the receiver in the activity so that the receiver can send data and the running activity can receive the data :-
C2dmreceiver c2dmr = new C2dmreceiver();
Registration.this.registerReceiver(c2dmr, new IntentFilter());
I don't know what to put inside the IntentFilter(), also what else I have to put in the code of the activity and the code of the receiver so that while the activity is running and some C2DM message comes the receiver can send the data to the running activity.
So, please tell me the code that is to put in the activity and in the receiver and may also be in the manifest so that the data from the receiver could be send to running activity.
Any advice is highly appreciated.
First of all it's not the best idea to subscribe c2dm receiver in activity. Do it in manifest. For passing data to activity you can create static string field in Activity and set you String there.
You can do something like this:
in Activity
public static YourActivity mThis = null;
#Override
protected void onResume() {
super.onResume();
mThis = this;
}
#Override
protected void onPause() {
super.onPause();
mThis = null;
}
In your BroadcastReceiver:
#Override
public void onReceive(Context context, Intent intent) {
...
if (YourActivity.mThis != null) {
((TextView)YourActivity.mThis.findViewById(R.id.text)).setText("received c2dm");
}
else {
...
}

Listening to incoming SMS after broadcast is unregistered: nice feature or broadcastreciever's bug?

I have an application which should watching incoming SMS (scan SMS text and show toast messages based on content) , even after my application is closed. The desired functionality is app watching all incoming SMS until app will not moved from device, and now it works like this. But I think, if I will need soon, to "switch of" this "watching eye", how I could to do this?
public class SmsReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null)
{
//do some action
}
}
BroadcastReceiver's code is a separate unit SMSReceiver.java. From main Activity I do not call this receiver, do not register and do not unregister. It's just working independently. Amazing.
So.. how I can ti stop this receiver??
The most common way to register/unregister BroadcastReceivers is to use the onResume() and onPause() methods of your Activity.
Firstly remove the <intent-filter> from your manifest, i.e., delete this section......
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECIEVED"></action>
</intent-filter>
Then add something like this to your Activity....
public class MyActivity extends Activity {
private final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private SMSReceiver smsReceiver = null;
private Boolean isReceiverRegistered = false;
#Override
protected void onResume() {
if (!isReceiverRegistered) {
registerReceiver(smsReceiver, new IntentFilter(ACTION_SMS_RECEIVED));
isReceiverRegistered = true;
}
}
#Override
protected void onPause() {
if (isReceiverRegistered) {
unregisterReceiver(smsReceiver);
isReceiverRegistered = false;
}
}
}
You'll have to take the BroadcastReceiver out of your Manifest to control it such as using it in a Service or Activity. When its in the Manifest its always on.

Categories

Resources