Why does this Broadcast Receiver work in Android? - android

I am a Beginner in programming in Android and now I am sitting in front of this problem: I would code a Broadcast Receiver, which gets fired whenever the Phone gets charged or "discharged". So, registered the Receiver in the Manifest.xml:
<receiver
android:name=".Starter"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
In the Class of the Broadcast Receiver, I wrote a Toast into the onReceive()-Method, which should be performed, when the Receiver would work:
> public class Starter extends BroadcastReceiver {
>
> #Override
> public void onReceive(Context context, Intent intent) {
> Toast.makeText(context,"blablabla",Toast.LENGTH_LONG).show();
> }
> }
I am so thankful for every Help, LG

When using a BroadcastReceiver, it must be registered with the class that will listen for broadcasts.
This is done using Context.registerReceiver() (https://developer.android.com/reference/android/content/Context#registerreceiver)
or
LocalBroadcastManager.getInstance(...).registerReceiver(...) (https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager).
Create IntentFilters that will listen for the particular broadcast.
Register your receiver in onResume() in a class that extends Activity or Fragment.
class MainActivity extends Activity
{
Starter myReceiver = new Starter(); // This is your class that extends BroadcastReceiver
#Override
public void onResume()
{
super.onResume();
// Create IntentFilters that will listen for certain actions:
IntentFilter intentFilterConnected = new IntentFilter(Intent.ACTION_POWER_CONNECTED);
IntentFilter intentFilterDisconnected = new IntentFilter(Intent.ACTION_POWER_DISCONNECTED);
// Then pass these intents to registerReceiver():
registerReceiver(myReceiver, intentFilterConnected);
registerReceiver(myReceiver, intentFilterDisconnected);
}
}
Now myReceiver's onReceive() will execute when MainActivity receives the broadcasts matching the IntentFilters.
Note: If the class that instantiates myReceiver does not extend Activity or Fragment, then you will need to use LocalBroadcastManager.getInstance(...).registerReceiver(...).

Related

Launch single BroadcastReceiver form another application

I created an Application that shares a BroadcastReceiver that launches a Service.
The app that holds the receiver doesn't have activities, there are the receiver class and the services.
Here are the manifest declaration:
<service
android:name=".services.PrintService"
android:enabled="true"
android:exported="true" />
<receiver
android:name=".receivers.MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="art.bridge.PRINT_MESSAGE" />
</intent-filter>
</receiver>
Receiver class
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Log.d(ArtAppl.name , "Receiver reached");
Intent print = new Intent(context, PrintService.class);
if(intent.getStringExtra("message") != null)
print.putExtra("message",intent.getStringExtra("message"));
else
print.putExtra("message","Message not found");
context.startService(print);
}
}
Form an another app, i try to launch the receiver like following:
Intent bReceiver = new Intent("art.bridge.PRINT_MESSAGE");
sendBroadcast(bReceiver);
But the receiver doesn't run.
Am I missing something? Do I have to set another action in the manifest?
Could it be that you need to include Intent.FLAG_INCLUDE_STOPPED_PACKAGES as a flag?
See: How to Send BroadCast from one app to another app

Broadcasting intent from BroadcastReceiver to Activity

I have registered a BroadcastReceiver in manifest:
<receiver android:name=".OrderReceiver" android:permission="com.google.android.c2dm.permission.SEND" android:exported="true">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.gndp" />
</intent-filter>
</receiver>
and in OrderReceiver class I'm trying to broadcast a received intent this way:
public class OrderReceiver extends BroadcastReceiver {
public void onReceive(Context mContext, Intent intent) {
if(intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
intent.setAction("com.gndp.device.REGISTERED");
mContext.sendBroadcast(intent); //BAZINGA
}
}
This broadcasted intent(BAZINGA) is received in this class(OrderReceiver) but not in another activity where i want to receive it. Here's the activity:
public class RegisterActivity extends Activity {
private BroadcastReceiver deviceRegisteredBroadcastReciever;
#Override
onCreate(){
...
deviceRegisteredBroadcastReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//broadcast never reach here<----PROBLEM
}
}
#Override
onResume() {
...
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(mContext);
lbm.registerReceiver(deviceRegisteredBroadcastReciever, new IntentFilter("com.gndp.device.REGISTERED"));
}
}
Have tried a lot of things including sending broadcast by instance of LocalBroadcastManager, using an inner class instead of BroadcastReceiver in the activity.
RegisterActivity is in foreground when OrderReceiver receives its first broadcast and it stays in foreground.
You send a global broadcast in the OrderReceiver by calling sendBroadcast of Context class and trying to receive this with LocalBroadcastManager.
You should either broadcast with LocalBroadcastManager or register ordinary BroadcastReceiver with Activity.registerReceiver method in the RegisterActivity.

Register a Local BroadcastReceiver in AndroidManifest.xml?

Is there anyway to register a BroadcastReceiver in AndroidManifest.xml and receives broadcast that is send by a LocalBroadcastManager?
Currently I must call
registerReceiver(BroadcastReceiver receiver, IntentFilter filter)
to register a Receiver, declare in AndroidManifest.xml won't work. But this means I must know exactly the receiver's package name and class name, not just the intent filter. Is it possible to declare the receiver in the manifest file?
following is my current code.
AndroidManifest.xml:
...
<receiver
android:name="com.example.test.MessageReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="com.m2x.test.intent.MESSAGE_RECEIVED" />
</intent-filter>
</receiver>
...
MainActivity.java:
Intent intent = new Intent();
intent.setAction("com.m2x.test.intent.MESSAGE_RECEIVED");
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(mContext.get());
manager.sendBroadcast(intent);
MessageReceiver.java
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.m2x.test.intent.MESSAGE_RECEIVED")) {
Toast.makeText(context, "user message received", Toast.LENGTH_SHORT).show();
}
}
}
No, you can't.
The local BroadcastReceiver isn't a real BroadcastReceiver, basically its a list of callbacks functions.
You can check the source code of LocalBroadcastManager.java.

Android BroadcastReceiver in separate project

I'm developing two Android applications.
The first one calls broadcast receiver from activity.
The second one contains broadcast receiver that is called from first application.
I've manage to do broadcast call when it is in the same application with caller activity.
But when I take receiver to separate project it doesn't work. What should I change?
This is how I register receiver:
<receiver
android:name=".TestReceiver"
android:enabled="true"
android:exported="true"
android:process=":deltaFO">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="com.myapp.intent.action.FILE_OPERATION" />
</intent-filter>
</receiver>
This is how I send intent
Intent intent = new Intent("com.myapp.intent.action.FILE_OPERATION");
intent.putExtra("operation", operation);
context.sendBroadcast(intent);
This is class that receives intent:
public class TestReceiver extends BroadcastReceiver{
public final String TAG="TestReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG,"EXTERNAL BROADCAST...");
}
}

Android BroadcastReceiver within Activity

I'm just trying this little sample project, all it does:
Activity one has a Button that sends a Broadcast. Activity two displays a toast when received.
Below is the code, the Broadcast is never received. What do I do wrong?
Sending the Broadcast
public class SendBroadcast extends Activity {
public static String BROADCAST_ACTION = "com.unitedcoders.android.broadcasttest.SHOWTOAST";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void sendBroadcast(View v){
Intent broadcast = new Intent();
broadcast.setAction(BROADCAST_ACTION);
sendBroadcast(broadcast);
}
}
Receiving it
public class ToastDisplay extends Activity {
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT);
}
};
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction(SendBroadcast.BROADCAST_ACTION);
registerReceiver(receiver, filter);
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(receiver);
super.onPause();
}
}
Manifest
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SendBroadcast" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ToastDisplay">
<intent-filter>
<action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"></action>
</intent-filter>
</activity>
</application>
What do I do wrong?
The source code of ToastDisplay is OK (mine is similar and works), but it will only receive something, if it is currently in foreground (you register receiver in onResume). But it can not receive anything if a different activity (in this case SendBroadcast activity) is shown.
Instead you probably want to startActivity ToastDisplay from the first activity?
BroadcastReceiver and Activity make sense in a different use case. In my application I need to receive notifications from a background GPS tracking service and show them in the activity (if the activity is in the foreground).
There is no need to register the receiver in the manifest. It would be even harmful in my use case - my receiver manipulates the UI of the activity and the UI would not be available during onReceive if the activity is not currently shown. Instead I register and unregister the receiver for activity in onResume and onPause as described in
BroadcastReceiver documentation:
You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml.
Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT);
makes the toast, but doesnt show it.
You have to do Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();
Extends the ToastDisplay class with BroadcastReceiver and register the receiver in the manifest file,and dont register your broadcast receiver in onResume() .
<application
....
<receiver android:name=".ToastDisplay">
<intent-filter>
<action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
</intent-filter>
</receiver>
</application>
if you want to register in activity then register in the onCreate() method e.g:
onCreate(){
sentSmsBroadcastCome = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "SMS SENT!!", Toast.LENGTH_SHORT).show();
}
};
IntentFilter filterSend = new IntentFilter();
filterSend.addAction("m.sent");
registerReceiver(sentSmsBroadcastCome, filterSend);
}
You need to define the receiver as a class in the manifest and it will receive the intent:
<application
....
<receiver android:name=".ToastReceiver">
<intent-filter>
<action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
</intent-filter>
</receiver>
</application>
And you don't need to create the class manually inside ToastDisplay.
In the code you provided, you must be inside ToastDisplay activity to actually receive the Intent.
I think your problem is that you send the broadcast before the other activity start ! so the other activity will not receive anything .
The best practice to test your code is to sendbroadcast from thread or from a service so the activity is opened and its registered the receiver and the background process sends a message.
start the ToastDisplay activity from the sender activity ( I didn't test that but it may work probably )
You forget to write .show() at the end, which is used to show the toast message.
Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();
It is a common mistake that programmer does, but i am sure after this you won't repeat the mistake again... :D
Your also have to register the receiver in onCreate(), like this:
IntentFilter filter = new IntentFilter();
filter.addAction("csinald.meg");
registerReceiver(receiver, filter);

Categories

Resources