Why my BroadcastReceiver doesn't work? - android

I'm trying to learn to use Android BroadcasReceiver.
I wrote this code but It doesn't work... I tryed for example to change the Time etc...
What is it wrong?
I added in the Manifest:
<receiver android:name="com.example.broadcastreceiverspike.Broadcast" >
<intent-filter android:priority="100">
<action android:name="android.intent.action.ACTION_SCREEN_ON" />
<action android:name="android.intent.action.ACTION_SCREEN_OFF" />
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>
My simple BroadcasReceiver:
public class Broadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BROADCAST", "It worked");
Toast.makeText(context, "BROADCAST", Toast.LENGTH_LONG).show();
}
}
My Main Activity (default main Activity)
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

I solved!
"unlike other broad casted intents, for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON you CANNOT declare them in your Android Manifest! I’m not sure exactly why, but they must be registered in an IntentFilter in your JAVA code"
http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
Manifest
<receiver android:name=".Broadcast" >
<intent-filter>
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>
Main Activity Class
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// INITIALIZE RECEIVER
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new Broadcast();
registerReceiver(mReceiver, filter);
}
}
My broadcast receiver
public class Broadcast extends BroadcastReceiver {
public static String TAG = "BROADCAST";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_TIME_CHANGED))
{
Log.d(TAG, "BROADCAST Cambio di orario");
Toast.makeText(context, "BROADCAST Cambio di orario", Toast.LENGTH_LONG).show();
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// DO WHATEVER YOU NEED TO DO HERE
Log.d(TAG, "BROADCAST Screen OFF");
Toast.makeText(context, "Screen OFF", Toast.LENGTH_LONG).show();
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// AND DO WHATEVER YOU NEED TO DO HERE
Log.d(TAG, "BROADCAST Screen ON");
Toast.makeText(context, "BROADCAST Screen ON", Toast.LENGTH_LONG).show();
}
}
}

Did you add the needed premissions?
uses-permission android:name="android.permission.READ_PHONE_STATE"
This is a receiver to handle when screen is off or on or locked:
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
}
else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT))
{
}
}
}
this is the manifest:
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.SCREEN_ON" />
</intent-filter>
</receiver>

Check out this tutorial about broadcast receivers.
Update:
I'm not sure you're using this tutorial, because there are lots of useful stuff in this tutorial, like this:
#Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
// handler for received Intents for the "my-event" event
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
In other words, you've created a custom broadcast receiver class, but you haven't used it.
And also please check this.

I had the same problem and I fixed it (tested on 4.3 and 5.1). I WAS able to declare "android.intent.action.USER_PRESENT" inside the manifest, as long as you have the READ_PHONE_STATE permission, it is OK!! My mini app consists of a Broadcast receiver that reacts to the screen ON/OFF state, and runs a background service that does continuous voice recognition. If the screen is off, the recognition is turned off. Here is the code, enjoy: MANIFEST:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> <receiver android:name="classes.VoiceLaunchReceiver" >
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
BROADCAST RECEIVER:
public class VoiceLaunchReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
Intent service = new Intent(ctx, VoiceLaunchService.class);
// service.putExtra(action, true);
Log.i("joscsr","Incoming Voice Launch Broadcast...");
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Log.i("joshcsr", "************\nCSR Resumed (BC)\n************");
ctx.startService(service);
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.i("joshcsr", "************\nCSR STOPPED by SCREEN (BC)\n************");
ctx.stopService(service);
}
}
}
As you can imagine, my USER_PRESENT broadcast receiver is not registered anywhere else. I do register ACTION_SCREEN_OFF and ON in the onCreate method of my service, who was triggered by my receiver.
#Override
public void onCreate() {
super.onCreate();
//Register screen ON/OFF BroadCast
launcher=new VoiceLaunchReceiver();
IntentFilter i=new IntentFilter(Intent.ACTION_SCREEN_OFF);
i.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(launcher,i);
Log.d("joshcsr","VoiceLaunch Service CREATED");
}
Finally I unregister the screen on/off in the onDestroy() of my service:
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(launcher);}

Related

Update UI from static BroadcastReceiver

I've checked this example of how to handle network connectivity changes:
Android Check Internet Connection and found a very nice piece of code of how to handle this changes:
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context); //some internal class to determinate which type is connected
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
To make this thing work I need to declare this BroadcastReceiver inside my manifest file:
<application ...>
...
<receiver
android:name="net.viralpatel.network.NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
...
</application>
Now I want to update UI, when wifi/mobile data is connected.
I can either make the NetworkChangeReceiver class inner static or external. But what I need is that I can work with my MainActivity UI from public void onReceive. How I can do this?
The answer was easy. I don't need to register my broadcast in order to get broadcast about connectivity change:
private BroadcastReceiver networkConnectivityReciever = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
NetworkInfo currentNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (dialog != null) {
if(currentNetworkInfo.isConnected()){
dialog.dismiss();
webView.reload();
}else{
dialog.show(((MainActivity) context).getSupportFragmentManager(), "");
}
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(networkConnectivityReciever,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(networkConnectivityReciever);
}
And only thing I need in manifest is this:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Broadcastreceiver not receiving?

I am trying to pass values from service to activity using broadcast
I am using following code to call broadcast in service
Intent i = new Intent();
i.putExtra("test",result);
sendBroadcast(i);
And receiving in main activity using following code
public class myreciver extends BroadcastReceiver{
public String data =null;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String datapassed = intent.getStringExtra("test");
}
}
In Main Activity
myreciver m = new myreciver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(m, intentFilter);
but my receiver is not called.
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.pragadees.restex" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MainActivity$myreciver" >
</receiver>
<service
android:name=".MyIntentService"
android:exported="false" >
</service>
<service
android:name=".MyService"
android:enabled="true"
android:exported="false" >
</service>
<activity
android:name=".display"
android:label="#string/title_activity_display" >
</activity>
</application>
</manifest>
Action missing in Intent which is passing to sendBroadcast method.do it as:
Intent i = new Intent(MyService.MY_ACTION); //<< pass Action to Intent
i.putExtra("test",result);
sendBroadcast(i);
use broad cast like this
Intent i = new Intent("Broadcastname");
context.sendBroadcast(i);
and now receive broad cast like this way
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter intentFilter = new IntentFilter("Broadcastname");
BroadcastReceiver Receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// to your work here
}
});
}
};
this.registerReceiver(Receiver, intentFilter);
finally unregister in onstop() method
#Override
protected void onStop() {
// TODO Auto-generated method stub
if (Receiver != null) {
this.unregisterReceiver(this.Receiver);
}
super.onStop();
}
Android's BroadcastReceiver is part of a framework that allows activities and services to send data to one another, even if they belong to separate apps. This is how apps share data with one another, such as when you share a picture from your gallery to Facebook or G+. However, this extensive capability means that you have to be careful about how you filter your requests, which means that it can be harder to just send a quick message from inside your own app.
If you don't need to worry about receiving data from other apps, then you can use the LocalBroadcastManager, which is an implementation of BroadcastReceiver that is confined inside of your own app's jurisdiction. It can't send or receive intents from outside your app. Its interface is nearly identical to BroadcastReceiver's:
public class MyActivity extends Activity {
private LocalBroadcastManager mBroadcastManager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBroadcastManager = LocalBroadcastManager.getInstance(this);
//Build an intent filter so you only receive relevant intents
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("Test from Service to Activity");
//Register a new BroadcastReceiver with the LocalBroadcastManager
mBroadcastManager.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String dataPassed = intent.getStringExtra("test");
}
}, intentFilter);
//If you ever want to send a broadcast, use this:
Intent sendIntent = new Intent(this, MyService.class);
sendIntent.setAction("Test from Activity to Service");
sendIntent.putExtra("test", "This is a test from Activity!");
mBroadcastManager.sendBroadcast(sendIntent);
}
}
//Then in your Service...
public class MyService extends Service {
private LocalBroadcastManager mBroadcastManager;
public void onCreate() {
mBroadcastManager = LocalBroadcastManger.getInstance(this);
}
public int onStartCommand(Intent intent, int flags, int startId) {
//Build intent filter
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("Test from Activity to Service");
mBroadcastManger.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String dataPassed = intent.getStringExtra("test");
}
}, intentFilter);
//To send data to the activity:
Intent sendIntent = new Intent(this, MyActivity.class);
sendIntent.setAction("Test from Service to Activity");
sendIntent.putExtra("test", "This is a test from Service!");
mBroadcastManager.sendBroadcast(sendIntent);
}
}

Listening for ACTION_DREAMING_STOPPED

How would I get my app to listen for when DayDream stops. When the system stops dreaming it sends the ACTION_DREAMING_STOPPED string out. I have added a BroadcastReceiver in my OnResume and onCreate and neither are used when DayDream stops. So where should I put my listener? I do apologize if I am calling something by its wrong name, I haven't worked with DayDream before.
#Override
protected void onResume() {
mDreamingBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_DREAMING_STOPPED)) {
// Resume the fragment as soon as the dreaming has
// stopped
Intent intent1 = new Intent(MainActivity.this, MainWelcome.class);
startActivity(intent1);
}
}
};
super.onResume();
}
The BroadcastReceiver can be created in your onCreate.
Ensure you register the receiver with: registerReceiver(receiver, filter) and that you've got the intent-filter inside your AndroidManifest.xml.
Sample:
MainActivity.java
public class MainActivity extends Activity
{
private static final String TAG = MainActivity.class.toString();
private BroadcastReceiver receiver;
private IntentFilter filter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, TAG + " received broacast intent: " + intent);
if (intent.getAction().equals(Intent.ACTION_DREAMING_STOPPED)) {
Log.d(TAG, "received dream stopped");
}
}
};
filter = new IntentFilter("android.intent.action.DREAMING_STOPPED");
super.registerReceiver(receiver, filter);
}
}
AndroidManifest.xml
<activity
android:name="com.daydreamtester.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.DREAMING_STOPPED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Android - ACTION_PACKAGE_FIRST_LAUNCH filter not working

I trying to detect my application run at first time. I used Broadcast Receiver to do this. It works fine with ACTION_PACKAGE_REPLACED. But it doesn't work when I use ACTION_PACKAGE_FIRST_LAUNCH intent. I'm using Android 4.3
This is my Activity
public class MainActivity extends Activity {
BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
broadcastReceiver = new TestBroadcast();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_FIRST_LAUNCH);
intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
intentFilter.addDataScheme("package");
registerReceiver(broadcastReceiver, intentFilter);
}
}
This is my AndroidManifest.xml
<receiver android:name="com.example.TestBroadcast" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_FIRST_LAUNCH" />
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
And TestBroadcast class
public class TestBroadcast extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_PACKAGE_FIRST_LAUNCH)) {
Toast.makeText(context, "Application installed",
Toast.LENGTH_SHORT).show();
}
}
}
Applications would receive these intents. These intents are broadcasted only to Play Store.

BroadcastReceiver for Screen On/Off not working

I am trying to use BroadcastReceiver but it is not working, please help me to solve this problem.
MyReceiver.java
package com.example.broadcast_receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.i("[BroadcastReceiver]", "Screen ON");
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcast_receiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name=".MyReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action.SCREEN_OFF"/>
</intent-filter>
</receiver>
<activity
android:name="com.example.broadcast_receiver.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
BroadcastReceiver not working and not making any log, please help me to solve this problem.
Hey try using dynamic calling of broadcast,I tried this it will surly work...
public class MainActivity extends Activity {
//Create broadcast object
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
//When Event is published, onReceive method is called
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("[BroadcastReceiver]", "Screen ON");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
}
If you want this receiver to be called by the system, you would need to export it. You set exported = "false", change this to true or remove exported entirely and this will start working. Normally this would be insecure, but as both SCREEN_ON and SCREEN_OFF are protected-broadcasts, and you verify the actions, only more trusted system code can send them too you, so it's pretty safe.
Sadly this wont work in this case as the intents broadcast have the following flags:
Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND
Can you try with getting battery value:
public class Broadcast extends Activity {
//Create broadcast object
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
//When Event is published, onReceive method is called
#Override
public void onReceive(Context context, Intent intent) {
//Get battery percentage
int batterylevel = intent.getIntExtra("level", 0);
//get progressbar
ProgressBar myprogressbar = (ProgressBar) findViewById(R.id.progressbar);
myprogressbar.setProgress(batterylevel);
TextView tv = (TextView) findViewById(R.id.textfield);
//Set TextView with text
tv.setText("Battery Level: " + Integer.toString(batterylevel) + "%");
}
});
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast);
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}

Categories

Resources