I am unable to send a Broadcast from one activity to other activity please see the code below. There are two buttons one for send Broadcast and other is for receiving Broadcast. I have tried following code. But my Receiver activity is running only when I click on checkBrodcast button.
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
sendBrodcast = (Button) findViewById(R.id.send_brodcast);
checkBrodcast = (Button) findViewById(R.id.check_brodcast);
sendBrodcast.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.w("Check", "inside send broadcast");
Intent broadcast = new Intent();
broadcast.setAction("BROADCAST_ACTION");
broadcast.addCategory(Intent.CATEGORY_DEFAULT);
sendBroadcast(broadcast);
}
});
checkBrodcast.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, Receiver.class);
startActivity(intent);
}
});
}
}
public class Receiver extends Activity {
BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.w("Check", "Inside On Receiver");
Toast.makeText(getApplicationContext(), "received",
Toast.LENGTH_LONG).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter();
filter.addAction("BROADCAST_ACTION");
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(br, filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(br);
}
}
The way you have Initiated the BroadCast is fine. You just need to change the way you intercept this Broadcast.
INITIATE A BROADCAST
Intent broadcast = new Intent();
broadcast.setAction("BROADCAST_ACTION");
broadcast.addCategory(Intent.CATEGORY_DEFAULT);
sendBroadcast(broadcast);
INTERCEPT IT
A) CREATE A RECEIVER
BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.w("Check", "Inside On Receiver");
Toast.makeText(getApplicationContext(), "received",
Toast.LENGTH_LONG).show();
}
};
B) REGISTER RECEIVER - Do this onCreate Activity Call Back
registerReceiver(br , new IntentFilter("BROADCAST_ACTION"));
Broadcast receivers registered this way(SINGLETON DECLARATION and NOT IN MANIFEST) - do not receive broadcasts unless the containing app is running. But as in your case you are firing a broadcast message onClick event, so the the app must be running. So I guess it is safe to assume that your receiver set up using this method, will work fine - provided the class in which you declared your receiver is created and exists in the activity stack, before you fire a broadcast from a different activity.
This is because you're not declaring your broadcast receiver in your Android Manifest. Dynamically registered receivers well not receive broadcasts unless the containing app is running.
If you want the second activity to get the broadcasts without having to click the button to start the app, then add the appropriate broadcast receiver to the second activities android manifest.
If you want to broadcast data from one activity to another, simply make use of Intent. In the light of your case simply call finish() in your onClickListener() and then in the onDestroy method of your second activity create Intent object and broadcast data as intent extra then, use intent.getExtra() method on onReceive() method of your broadcastReceiver class.
For more details:
follow this tutorial
The problem is with your manifest. You have to register your receiver in your Manifest like this:
<receiver android:name="MyReceiver" >
<intent-filter>
<action android:name="com.android.mybroadcast" />
</intent-filter>
</receiver>
But anyway, personally, I don't like how you are building the broadcast receiver structure.
You should create a class that extendes from BroadcastReceiver like:
public class MyBroadcastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Your receiver!!!!.",
Toast.LENGTH_LONG).show();
}
}
Dont forget to set up your manifest:
<receiver android:name="MyBroadcastReceiver" >
</receiver>
And now the class from you are calling:
public class AlarmActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startAlert(View view)
{
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
}
}
Something like that!!!
Related
I have a broadcast receiver that gets triggered on geofencing events and either "clocks in" or "clocks out" with the server. If my application's "Attendance" activity is already open I would like it to display the clocking status change but I don't want the Broadcast Receiver to start the activity if it's not open - in other words display the change "live" while the activity is open only.
The way I imagine doing this is with the Broadcast Receiver sending an Intent to the activity but name "startActivity()" doesn't sound encouraging unless there are any special flags I can pass to prevent starting an Activity that isn't already open - I can't seem to find any.
The other option would be to constantly poll the value while the activity is open but it doesn't seem optimal so I would only use it if there wasn't another way and I can't think of a reason why it couldn't be possible with Intents.
There are several different ways to accomplish the same task. One is registering a listener like the following example:
MainActivity
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Receiver.setOnReceiveListener(new Receiver.OnReceiveListener() {
public void onReceive(Context Context, Intent intent)
{
//Do something.
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
Receiver.setOnReceiveListener(null);
}
}
Receiver
public class Receiver extends BroadcastReceiver
{
private static OnReceiveListener static_listener;
public static abstract interface OnReceiveListener
{
public void onReceive(Context context, Intent intent);
}
public static void setOnReceiveListener(OnReceiveListener listener)
{
static_listener = listener;
}
#Override
public final void onReceive(Context context, Intent intent)
{
if(static_listener != null) {
static_listener.onReceive(context, intent);
}
}
}
Just have your BroadcastReceiver send a broadcast Intent. Your Activity should register a listener from this broadcast Intent and if it gets triggered, it can update the UI.
Here's an example:
Declare a private member variable in your Activity:
private BroadcastReceiver receiver;
In Activity.onCreate(), register the BroadcastReceiver:
IntentFilter filter = new IntentFilter();
filter.addAction("my.package.name.CLOCK_STATUS_CHANGE");
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Here you can update the UI ...
}
};
registerReceiver(receiver, filter);
And in onDestroy() you can unregister it (probably not necessary, but cleaner):
if (receiver != null) {
unregisterReceiver(receiver);
receiver = null;
}
In your BroadcastReceiver that detects the geofencing event, you should create and send a broadcast Intent:
Intent broadcastIntent = new Intent("my.package.name.CLOCK_STATUS_CHANGE");
sendBroadcast(broadcastIntent);
I have developed an app that receives a specific text message and then do a pre-defined task. This app works fine when it is running. but when it is closed it does not do the pre-defined task. I believe there is some problem that my app do not receive broadcast when it is closed. maybe i'm not properly registering the receiver in the manifest file.
I have two classes. one is SMSReceiver that extends the broadCast Receiver. and the second one is MainActivity that is calling the broadcast receiver to receive the text message and perform a specific task.
My manifest file is:
<receiver android:name=".SMSReceiver" android:exported="true"
android:enabled="true" android:directBootAware="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity">
</activity>
SMSReceiver Class Code:
public class SMSReceiver extends BroadcastReceiver {
public String number;
public String nn;
public String v;
#Override
public void onReceive(Context context, Intent intent) {
}
}
MainActivity class code
public class MainActivity extends AppCompatActivity{
public String r_num;
Button btn;
EditText msg;
EditText num;
IntentFilter intentFilter;
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//MYCODE
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction("SMS_RECEIVED_ACTION");
btn = (Button) this.findViewById(R.id.sendbtn);
msg = (EditText) this.findViewById(R.id.message);
num = (EditText) this.findViewById(R.id.numbertxt);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}} });
}
private void sendMsg(String n, String m) {
}
protected void onResume()
{
registerReceiver(intentReceiver,intentFilter);
super.onResume();
}
protected void onPause()
{
unregisterReceiver(intentReceiver);
super.onPause();
}}
This code works fine when my app is running. i want my app to respond to the message even when the app is closed/not running. Thanks in advance
Remove broadcast receiver from MainActivity. In SMSReceiver's onReceive() start MainActivity instead sending broadcast. Put extra datas to intent and receive it in MainActivity's onNewIntent().
Intent intent = Intent(context, MainActivity.java)
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
context.startActivity(intent)
In MainActivity override onNewIntent(). Put broadcast receiver's code in MainActivity into onNewIntent()
Or put this code inside SMSReceiver instead sending broadcast.
if(v.equalsIgnoreCase("call.me")) {
Toast.makeText(context, "Generating Call, Please Wait", Toast.LENGTH_LONG).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(number));
context.startActivity(callIntent);
}
put extras to intent from SMSReceiver like this
intent.putExtra("message", str);
intent.putExtra("me", v);
intent.putExtra("num", number);
receive it from onNewIntent() like this
Bundle bundle = intent.getExtras();
String message = bundle.getString("message");
String me = bundle.getString("me");
String number = bundle.getString("num");
I have created a BroadCast Receiver to notify the GPS state as below :
public class GpsLocationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
Toast.makeText(context, "asdsadasdsaD", Toast.LENGTH_SHORT).show();
}
}
Receiver in Manifest as below :
<receiver android:name=".utility.GpsLocationReceiver">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Now, the issue is that What if I want to check gps state only in single Fragment ? Right now it broadcasting for overall app.
Thanks.
ReceiverActivity.java
A Activity that watches for notifications for the event named "custom-event-name"
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
SenderActivity.java
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
in OnResume() of your fragment write
LocalBroadcastManager.getInstance(context).registerReceiver(gpsChangeReceiver , new IntentFilter("android.location.PROVIDERS_CHANGED"));
An in onPause() of your fragment write
LocalBroadcastManager.getInstance(context).unregisterReceiver(gpsChangeReceiver );
At bottom of your fragment write
private BroadcastReceiver gpsChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "asdsadasdsaD", Toast.LENGTH_SHORT).show();
}
};
Hi I developed one small android application in which I am using one activity one intent service and one broadcast receiver.
So my code looks like :
public class Main_Activity extends Activity {
private ResultReceiver resultReciver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_);
Log.i("***************************88", "inside activity on create");
IntentFilter filter = new IntentFilter("com.nilkash.broadcast.receiver");
resultReciver = new ResultReceiver();
registerReceiver(resultReciver, filter);
//LocalBroadcastManager.getInstance(this).registerReceiver(resultReciver, filter);
Intent intent = new Intent(this, ExampleService.class);
startService(intent);
}
public class ResultReceiver extends BroadcastReceiver{
public ResultReceiver()
{
}
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.i("**********************", "inside broadcast receiver: ");
}
}
}
And intent service
public class ExampleService extends IntentService{
public ExampleService(String value)
{
super(value);
}
public ExampleService()
{
super("");
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.i("********************************", "inside intetn reciver: ");
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.nilkash.broadcast.receiver");
//broadcastIntent.putExtra("value", "nilkash");
sendBroadcast(intent);
//LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
In manifest file I define service.
So my problem is that I start service from activity and its working fine. From service on intent receive I sent one broadcast receiver but it not listening inside my broadcast receiver.
Am i doing some thing wrong? Need Help. Thank you.
There is an error: sendBroadcast(intent);. Should be another intent object (broadcastIntent).
I would like to start a broadcast receiver from an activity. I have a Second.java file which extends a broadcast receiver and a Main.java file from which I have to initiate the broadcast receiver.
I also tried doing everything in Main.java as follows but didn't know how to define in manifest file...
Main.java:
public class Main extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String rec_data = "Nothing Received";
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if( intent.getStringExtra("send_data")!=null)
rec_data = intent.getStringExtra("send_data");
Log.d("Received Msg : ",rec_data);
}
};
}
protected void onResume() {
IntentFilter intentFilter = new IntentFilter();
//intentFilter.addDataType(String);
registerReceiver(myReceiver, intentFilter);
super.onResume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
this.unregisterReceiver(this.myReceiver);
}
}
If I cannot do everything in one class as above, how can I call the Broadcast Receiver from Main.java? Can anyone please let me know where I'm doing it wrong? Thanks!
use this why to send a custom broadcast:
Define an action name:
public static final String BROADCAST = "PACKAGE_NAME.android.action.broadcast";
AndroidManifest.xml register receiver :
<receiver android:name=".myReceiver" >
<intent-filter >
<action android:name="PACKAGE_NAME.android.action.broadcast"/>
</intent-filter>
</receiver>
Register Reciver :
IntentFilter intentFilter = new IntentFilter(BROADCAST);
registerReceiver( myReceiver , intentFilter);
send broadcast from your Activity :
Intent intent = new Intent(BROADCAST);
Bundle extras = new Bundle();
extras.putString("send_data", "test");
intent.putExtras(extras);
sendBroadcast(intent);
YOUR BroadcastReceiver :
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle extras = intent.getExtras();
if (extras != null){
{
rec_data = extras.getString("send_data");
Log.d("Received Msg : ",rec_data);
}
}
};
for more information for Custom Broadcast see Custom Intents and Broadcasting with Receivers
check this tutorial here you will get all help about broadcast including how to start service from activity or vice versa
http://www.vogella.de/articles/AndroidServices/article.html
For that you have to broadcast a intent for the receiver, see the code below :-
Intent intent=new Intent();
getApplicationContext().sendBroadcast(intent);
You can set the action and other properties of Intent and can broadcast using the Application context, Whatever action of Intent you set here that you have to define in the AndroidManifest.xml with the receiver tag.
Check this answer:
https://stackoverflow.com/a/5473750/928361
I think if you don't specify anything in the IntentFilter, you need to tell the intent the receiver class.