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.
Related
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();
}
};
I use broadcast receiver, and in Fragment.java i register. But it's not working.
My code:
Intent intent = new Intent("android.intent.action.LOGIN");
intent.putExtra("message", obj.getToken());
intent.setAction("com.sunrise.android.LOGIN");
loginView.getContext().sendBroadcast(intent);
In Fragment:
#Override
public void onResume() {
super.onResume();
informationStudentPresenter = new InformationStudentPresenter(this);
IntentFilter intentFilter = new IntentFilter("android.intent.action.LOGIN");
getActivity().registerReceiver(broadcastReceiver, intentFilter);
}
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getActivity(), "CLGT", Toast.LENGTH_SHORT);
if(intent.getAction().equalsIgnoreCase("com.sunrise.android.LOGIN")){
if(!"".equals(findToken())) {
informationStudentPresenter.getProfileStudent();
informationStudentPresenter.showToast();
}
}
}
};
Could you tell me where my mistake and how to fix it?
Thanks.
You're changing the Intent's action name right after initializing it with a different name. Then you're registering the broadcast receiver with an IntentFilter that waits for the old action name.
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!!!
I have 1 activity that I would like to start at different times with different variables from a Broadcast Receiver.
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase("tv.abcd.v4.ORIGINAL_VIDEO_SCENE")){
channelName = intent.getExtras().getString("com.abcd.Channel");
JSONObject json = new JSONObject(intent.getExtras().getString("com.abcd.Data"));
String incomingScene = json.getString("url");
scene.putExtra("channel", channelName);
scene.putExtra("url", incomingScene);
scene.addFlags(Intent.FLAG_FROM_BACKGROUND);
scene.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
scene.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scene);
}
I have the code to start the activity via Intent and in the activity receiver the extras to make data appear.
Intent intent = getIntent();
sceneUrl = intent.getStringExtra("url");
Log.d("Image.incomingscene.url",sceneUrl);
channelName = intent.getStringExtra("channel");
Log.d("Image.incomingSceneAvatar",networkAvatar);
image = (ImageView)findViewById(R.id.imageView1);
image.setScaleType(ScaleType.FIT_CENTER);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
Picasso.with(this).load(sceneUrl).skipMemoryCache().fit().into(image, new EmptyCallback() {
});
Now after that I want to start the same activity again from the Broadcast Reciever with different data. So i want the previous activity to get out the way and allow this new instance to start up.
How to accomplish this feat?
register another broadcast receiver from the activity. Then, when you want to kill it, send a broadcast message from the broadcast receiver that you mentioned .
In your broadcastReceiver do something like the following :
public static final String CLOSE_Activity= "com.mypackage.closeactivity";
and in yopr OnReceive method do like the following :
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("HIT OUTGOING");
Intent i = new Intent();
i.setAction(CLOSE_Activity);
context.sendBroadcast(i);
}
then in your activity craete a receviver and register it in the onResume method and unregeister it in the onPause method , like the following :
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(RECEIVER_Class.CLOSE_Activity)) {
finish();
}
}
}
activity onResume method :
#Override
public void onResume() {
registerReceiver(broadcastReceiver, new IntentFilter(RECEIVER_Class.CLOSE_Activity));
}
activity onPause method :
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Please give me some feedback
Hope that helps .
There are lots of posts out there on using BroadcastReceiver for receiving messages in an Activity that are broadcast from a Service. I've been through dozens and haven't found one that puts it all together. Bottom line is I can't get my Activity to receive broadcasts. Here's what I've done to date:
Service class broadcast:
Context context = this.getApplicationContext();
Intent intentB2 = new Intent(context, StationActivity.AudioReceiver.class);
intentB2.putExtra("Track", mSongTitle);
this.sendBroadcast(intentB2);
Log.i(TAG, "Broadcast2: " + mSongTitle);
Activity class declaration:
public String INCOMING_CALL_ACTION = "com.example.android.musicplayer.action.BROADCAST";
Activity class inline BroadcastReceiver:
public class AudioReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
// Handle receiver
Log.i(TAG, "Inner BroadcastReceiver onReceive()");
String mAction = intent.getAction();
if(mAction.equals(INCOMING_CALL_ACTION)) {
Log.i(TAG, "Inner BroadcastReceiver onReceive() INCOMING_CALL_ACTION");
}
}
};
Android manifest receiver declaration:
<receiver android:name=".StationActivity.AudioReceiver">
<intent-filter>
<action android:name="com.example.android.musicplayer.action.BROADCAST" />
</intent-filter>
</receiver>
What am I missing? Thanks in advance.
In your service:
Intent intentB2 = new Intent("some_action_string_id");
intentB2.putExtra("Track", mSongTitle);
sendBroadcast(intentB2);
Then in your activity:
public class MyActivity extends Activity {
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "Woot! Broadcast received!", Toast.LENGTH_SHORT);
}
};
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("some_action_string_id"); // NOTE this is the same string as in the service
registerReceiver(myReceiver, filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(myReceiver);
}
}
This is the common approach to receive broadcast events in activities. Note that we are registering the receiver when the activity is in the foreground and unregistering it when the activity is no longer visible.
replace your service code with below code and add String INCOMING_CALL_ACTION in your service or directly use it from activity class.
Context context = this.getApplicationContext();
Intent intentB2 = new Intent();
intentB2.setAction(INCOMING_CALL_ACTION);
intentB2.putExtra("Track", mSongTitle);
this.sendBroadcast(intentB2);
Log.i(TAG, "Broadcast2: " + mSongTitle);