I want to add a custom broadcast receiver to my app. and I have 3 methods that should do the broadcast. and in my onReceive method i want to identify which method did the broadcast. I have 3 methods like this
public void method01(View v){
int flag = 1;
Intent intent = new Intent();
intent.addFlags(flag);
broadcastIntent(intent);
}
public void method02(){
int flag = 2;
Intent intent = new Intent();
intent.addFlags(flag);
broadcastIntent(intent);
}
public void method03(){
int flag = 3;
Intent intent = new Intent();
intent.addFlags(flag);
broadcastIntent(intent);
}
and this is my broadcastIntent method
public void broadcastIntent(Intent intent){
sendBroadcast(intent);
}
in my onReceive method i use getFlags() method to get the flag value from the intent and send it through a if, else. but this do not work. any suggestion for improvements are welcome.
You can also use Actions to identify each one of you Intent objects.
String action1 = "first_sender";
String action2 = "second_sender";
Intent createIntent01(){
Intent intent01 = new Intent();
intent01.setAction(action1);
return intent01;
}
Intent createIntent02(){
Intent intent02 = new Intent();
intent01.setAction(action2);
return intent02;
}
And in your onReceive method you can use the getAction() method of intents to check which action was sent. This is in case you're not already using Actions.
[[EDIT]]
To register a BroadcastReceiver you need to define an IntentFilter and register the actions you wish to receive this way:
mBroadcastReceiver broadcastReceiver = new mBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(action1);
intentFilter.addAction(action2);
registerReceiver(broadcastReceiver,intentFilter);
class mBroadcastReceiver extends BroadcastReceiver{
public void onReceive(Context arg0, Intent arg1){
String action = arg1.getAction();
if(action.equals(action1)){
//do something
}else if(action.equals(action2)){
//do something else
}
}
The first problem is that ypu didn't specify a target for your intent. You can use intent filters and actions like rodkarom suggested or specify receiver's class directly (see in my example). In both cases you need either to declare your broadcast receiver in AndroidManifest.xml, or register it at runtime (see rodkarom's answer for a sample).
The method addFlags is used to specify some internal properties of Intent (like start activity corresponding to this intent in a new task) , so you cannot use it for your own data. The list of possible flags is in the documentation for setFlags method.
You can use putExtra to achieve your goal:
// an Activity is just an example
public class SenderActivity extends Activity {
// ...
void method01() {
int flag = 1;
Intent intent = new Intent(getApplicationContext(), Receiver.class); // any Context is acceptable here
intent.putExtra(MyReceiver.EXTRA_FLAG, flag); // any string will do well, you just need it to be the same here and in getExtra later
sendBroadcast(intent);
}
}
public class MyReceiver extends BroadcastReceiver {
public static final String EXTRA_FLAG = "your.package.name.EXTRA_FLAG";
// and in onReceive
public void onReceive (Context context, Intent intent) {
int flag = intent.getIntExtra(EXTRA_FLAG, someDefaultValue);
if (flag == 1) {
// ...
}
// ...
}
}
I found out the way to this and thought of sharing the code. this is the broadcasting done in my main activity for 2 different methods.
public void method1(View view){
Intent intent = new Intent();
intent.setAction("method1");
sendBroadcast(intent);
}
public void method2(View view){
Intent intent = new Intent();
intent.setAction("method2");
sendBroadcast(intent);
}
and this is how i receive it..
public class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast Intent Detected.",Toast.LENGTH_LONG).show();
}
this is how i registered it on manifest.
<receiver android:name="Receiver" >
<intent-filter>
<action android:name="method1" >
</action>
<action android:name="method2" >
</action>
</intent-filter>
</receiver>
Hope this will help if any one else came up with similar problem. and big thank you to every one who posted their answers here.
Related
I have 2 app, A and B, and i want send 2+2 from application A to B and in return i want to receive 4 from App B, please tell me the process and full code base.
1.From app A Trigger a broadCast1 with both of your numbers.
Intent intent = new Intent("com.myapps.appA");
intent.putExtra("num1",2);
intent.putExtra("num2",2);
sendBroadcast(intent);
now register the receiver for broadCast1 in App B, you can do this in onCreate of its Main activity.
private BroadcastReceiver broadcastReceiver1;
...
broadcastReceiver1 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
registerReceiver(broadcastReceiver1, new
IntentFilter("com.myapps.appA");
Inside onRecieve get both the numbers from the intent and Trigger another broadCast with the result i.e.
int num1 = intent.getIntExtra("num1",0);
int num2 = intent.getIntExtra("num2",0);
Intent intent2 = new Intent("com.myapps.appB");
intent2.putExtra("sum",num1+num2);
YourActivity.this.sendBroadcast(intent2);
Now Register the reciever for Broadcast2 Inside your App A, you can do this in onCreate of its Main activity.
private BroadcastReceiver broadcastReceiver2;
...
broadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
registerReceiver(broadcastReceiver2, new
IntentFilter("com.myapps.appB");
Inside its OnRecive() get the result
int sum = intent.getIntExtra("sum",0);
Most importantly don't forget to unregister the receivers in onStop on the activity
I want the service to perform a stopForeground and a stopSelf after the notification is clicked followed by the running of pendingIntent.
I have tried using a BroadcastReceiver which is never called as I checked during debugging. I have added it to manifest as well.
Intent intentHide = new Intent(this, StopServiceReceiver.class);
PendingIntent hide = PendingIntent.getBroadcast(this, (int) System.currentTimeMillis(), intentHide, PendingIntent.FLAG_CANCEL_CURRENT);
Added it to the builder
builder.setContentIntent(hide);
And the Broadcast Rec is done separately -
public class StopServiceReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 333;
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, TimerService.class);
context.stopService(service);
}
}
Manifest -
<receiver
android:name=".StopServiceReceiver"
android:enabled="true"
android:process=":remote" />
This is not working. The notification and the service both are alive.
Questions - Should I use addContent instead of setContentIntent ? If yes, then what should the parameters be ?
Is there anything I went wrong with? What could possibly be wrong with such kind of implementation? Thank you.
I had the same problem in the notification.
This code is working perfectly.
void creatnotifiaction()
{
public static final String STOP = "com.example.android";
public static final int REQUEST_CODE = 333;
filter = new IntentFilter();
filter.addAction(STOP);
Intent intentHide = new Intent(STOP);
PendingIntent hide = PendingIntent.getBroadcast(this,REQUEST_CODE,intentHide,PendingIntent.FLAG_CANCEL_CURRENT);
registerReceiver(broadcastReceiver, filter);
}
There no need to separate broadcast receiver use in same class.
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#SuppressLint("ResourceAsColor")
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d("notification", "Received intent with action " + action);
switch (action) {
case STOP:
//your code to stop notifications or service.
break;
}
});
Let me know if that work for you.
Thanks...Happy coding.
I am trying to start two services on reboot of the device using only one Broadcastreceiver. But only one service is called.
Here is my receiver:
public class FirstReciever extends BroadcastReceiver{
private static final String TAG8 = "Mytag";
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Log.i(TAG8, "Restarting App after boot");
Intent myServiceInent = new Intent(context, FirstReciever.class);
context.startService(myServiceInent);
Intent myServiceInent1 = new Intent(context, DbService.class);
context.startService(myServiceInent1);
}
}
}
To start an Activity use:
startActivity(intent);
To Start a Service use:
startService(intent);
first of all look at this.
Intent myServiceInent = new Intent(context, FirstReciever.class);
context.startService(myServiceInent);
you have given the reference of your FirstReciever.class, that should be a service.
and if that doesn't work than start a single service and start another service from first one...
I send a Broadcast by doing:
Intent intent = new Intent("com.usmaan.myApp.DATA_RECEIVED");
intent.putExtra("matchId", newRowId);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
This is the Service that wraps up the AsyncTask which runs Broadcasts the above:
<service
android:name=".services.DataService"
android:exported="false" />
In my Activity, I register a Receiver in onResume:
IntentFilter intentFilter = new IntentFilter("com.usmaan.myApp.DATA_RECEIVED");
registerReceiver(mDataReceiver, intentFilter);
The `BroadReceiver looks like this:
private class DataReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final long matchId = intent.getLongExtra("matchId", 0);
Toast.makeText(LaunchActivity.this, "" + matchId, Toast.LENGTH_LONG);
}
}
The onReceive is never fired. What am I doing wrong?
Either use LocalBroadcastManager in both places (sendBroadcast() and registerReceiver()), or do not use LocalBroadcastManager at all. Right now, you have a mismatched pair.
I'm stuck here at my previous struggle >> Prev. Struggle!
Raanan there helped! me a lot but then he I think went away as timing zone is different , now I'm stuck with my service code that I'm using to call my BroadcastReceiver() that is in the activity! and also I'm not getting with what parameter I should load the filter.addAction(action); in place of action??
Kinldy guide me!
CODE in the Server:
Toast.makeText(Server.this, hr +" , " +min, Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, andRHOME.class);
//intent.putExtra("sendMessage","1");
sendBroadcast(intent);
and CODE IN THE ACITIVITY(Broadcast Receiver)
private BroadcastReceiver ReceivefrmSERVICE = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "IN DA BroadCASTER",
Toast.LENGTH_LONG).show();
sendMessage("1");
}
};
IntentFilter filter = new IntentFilter();
You need to add these line to regiester your receiver for some action for example define a Global variable like this:
public static String NOTIFCATION_BROADCAST_ACTION = "com.your_packagename.UPDATE_NOTIFICATION_INTENT";
then register the action like this in your activity onCreate() Method.
IntentFilter filter = new IntentFilter();
filter.addAction(Global.NOTIFCATION_BROADCAST_ACTION);
registerReceiver(ReceivefrmSERVICE, filter);
Then send the broadcast from your service like this
Intent broadcast = new Intent();
broadcast.setAction(Global.NOTIFCATION_BROADCAST_ACTION);
sendBroadcast(broadcast);
Then in your broadcast Receiver filter this action like this
private BroadcastReceiver ReceivefrmSERVICE = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Global.NOTIFCATION_BROADCAST_ACTION)) {
//Do your stuff here :)
}
}
};