broadcast receiver not receiving Intent through Service - android

I'm trying to implement a Broadcast Receiver who should receive Intent from a Service which is running in the background, however it is not working.
In my main Activity I just bind the service and start it via onClick on a Button.
In my SpeechRecognizer Service class I create a new BroadcastReceiver (see code below).
public void onCreate() {
Log.d(TAG, "onCreate");
if (SpeechRecognizer.isRecognitionAvailable(this)){ //check if a SpeechRecognizer is available
this.sr = SpeechRecognizer.createSpeechRecognizer(this);
this.sr.setRecognitionListener(new listener());
commandsReceiver = new CommandsReceiver();
ConnectivityManager cm =(ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
testfilter = new IntentFilter();
registerReceiver(commandsReceiver,testfilter);
} else {
Toast.makeText(this,"Please install a SpeechRecognizer on your system.", Toast.LENGTH_LONG).show(); //alert if speech-recognizer is not installed on the device
Log.d(TAG, "no SpeechRecognizer available");
this.onDestroy();
}
}
In my onResult I do it like this:
Intent intent = new Intent();
intent.setAction(CommandsReceiver.TEST);
sendBroadcast(intent);
In my CommandsReceiver I just got a simple String and a Log message:
public class CommandsReceiver extends BroadcastReceiver {
public static final String TEST = "de.speech.TEST_INTENT";
#Override
public void onReceive(Context context, Intent intent) {
Log.d("BroadCastReceiver", "Intent received"+intent);
}
}
However I'm not getting the Log.d() message.
I hope you can help me out.

Seems you are creating an IntentFilter without any Action as
testfilter = new IntentFilter();
instead of,
testfilter = new IntentFilter(CommandsReceiver.TEST);
so, register your BroadCast using,
testfilter = new IntentFilter(CommandsReceiver.TEST);
registerReceiver(commandsReceiver,testfilter);

Related

I want to upload images (using asyncTask),but if my internet is down,i want to send a broadcast intent

I want to upload images (using asyncTask),but if my internet is down,i want to send a broadcast intent and upload images automatically when internet is connected next time. I have successfully uploaded images when internet is active, I saw many examples but none of them helped me.
i have a class UploadImages which extends AsyncTask
I made broadcast receiver class like this
public class MyBroadcastReceiver extends BroadcastReceiver {
ConnectivityManager connec;
#Override
public void onReceive(Context context, Intent intent) {
connec = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connec != null && (connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) ||(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED))
{
Intent intent1 = new Intent(context, UploadIntentService.class);
intent1.putExtra("", "index.html");
context.startService(intent);
}
}
}
Here is my UploadIntentService class
public UploadIntentService() {
super("uploadIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
new UploadImageToBucket().execute("");
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.alg.imgSave.MyBroadcastReceiver");
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra("RESPONSE_STRING", "1");
broadcastIntent.putExtra("RESPONSE_MESSAGE", "Uploaded");
sendBroadcast(broadcastIntent);
}
But this is not working
Please reference:
Broadcast receiver for checking internet connection in android app
The idea here would be that if your internet goes down, send the broadcast intent which this receiver is registered for, and once your internet connection changes this receiver will be launched and then you can make your request to upload the image.

Broadcastreceiver components are not allowed to bind to services in android

Here is what I am doing:
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
ConnectivityManager conn = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = conn.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (isConnected == true) {
// initChatHub();
Intent serviceIntent = new Intent(context, ChatService.class);
Toast.makeText(context, "Connected", 1000).show();
serviceIntent.putExtras(intent);
context.startService(serviceIntent);
context.bindService(serviceIntent, mServiceConnection,
Context.BIND_AUTO_CREATE);
} else {
Toast.makeText(context, "Disconnected", 1000).show();
}
}
when network state change then application becomes crash when i data-connection off then there is no Error coming when data connection On then app becomes crash and this Exception coming please suggest me how to fix it.
See here Context.bindService :
Note: this method can not be called from a BroadcastReceiver
component....
So, use BroadcastReceiver.peekService which return IBinder from running Service:
Intent serviceIntent = new Intent(context, ChatService.class);
context.startService(serviceIntent);
if (isConnected == true) {
IBinder binder = peekService(context, new Intent(context, ChatService.class));
Toast.makeText(context, "Connected", 1000).show();
if (binder != null){
mChatService = ((LocalBinder) binder).getService();
//.... other code here
}
}
The reason Android return this exception is Receiver lifecycle. It may be very short. If receiver binds service, receiver may not exist until result return. see here Receiver lifecycle.
The solution is starting another middle service. Let middle service to bind target service. This middle service can be existed until result return. And receiver can be killed in anytime.
There is another hack solution to skip Android NotAllowException. This exception check Context. If this Context comes from Receiver, then Android return Exception. Change your code
context.bindService(serviceIntent, mServiceConnection,
Context.BIND_AUTO_CREATE);
to
context.getApplicationContext.bindService(serviceIntent, mServiceConnection,
Context.BIND_AUTO_CREATE);
This hack solution won't keep receiver's life. If you think the result from binding service is not important. You can use this hack solution to skip NotAllowException.
You cannot call bindService from BroadcastReceiver. The alternate is :
Create an Application class (by extending Application class)
Create a function for starting and binding of service into you Application class
In broadcast receiver get instance of your application class and call function for starting service.
Sample Code:
public class MyApplication extends Application{
public void startService(){
Intent serviceIntent = new Intent(context, ChatService.class);
Toast.makeText(context, "Connected", 1000).show();
serviceIntent.putExtras(intent);
context.startService(serviceIntent);
context.bindService(serviceIntent, mServiceConnection,
Context.BIND_AUTO_CREATE);
}
}
// inside onReceive function
public void onReceive(Context context, Intent intent) {
ConnectivityManager conn = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = conn.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (isConnected == true) {
MyApplication app=(MyApplication)context.getApplicationContext();
app.initChatService();
} else {
Toast.makeText(context, "Disconnected", 1000).show();
}
}
Service.bindService() can not be called from a BroadcastReceiver component. I use Application Context,it is OK
I met same problem, when I was trying to access MQTT client from BroadcastReceiver like this:
public class BroadcastHelper extends BroadcastReceiver implements MqttCallbackExtended {
#Override
public void onReceive(Context context, Intent intent) {
MqttAndroidClient CLIENT;
mqtt_helper = new MQTThelper( context ); <--- problem was here
CLIENT = mqtt_helper.getMqttCLIENT();
CLIENT.setCallback( this );
mqtt_helper.MqttConnect();
}
//... all other functions omitted
}
Then I received NotAllowException and Broadcastreceiver components are not allowed to bind to services error.
So to solve this I had to pass context to the class where MQTT CLIENT is created and handled like this context.getApplicationContext() instead of context only.
full line:
mqtt_helper = new MQTThelper( context.getApplicationContext() );

Broadcast reciever not working from service

I am trying to use BroadcastReceiver inside my service but it is not working properly.
I am starting my service in an onCreate in my activity. Then in the services onCreate I am calling the following to register the Broadcast reciever:
IntentFilter filter = new IntentFilter();
registerReceiver(DataUpdateReceiver, filter);
Here's the broadcast receiver i am trying to register:
private BroadcastReceiver DataUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Test", Toast.LENGTH_LONG).show();
}
};
Then else where in the Activity I am trying to call this so therefor the Toast message will be displayed.
Intent i = new Intent();
sendBroadcast(i);
But the Toast is not being displayed, I have also tried logging but nothing shows up. If anyone could help me out on this it would be appreciated, ty.
In my opinion, you have to specify action (or actions), which fire onReceive() method. Something like this might help you:
IntentFilter filter = new IntentFilter("some_action");
registerReceiver(DataUpdateReceiver, filter);
...
Intent i = new Intent("some_action");
sendBroadcast(i);
Declare on top of the class
public final static String MY_RECEIVER_START = "com.yourcompanyname.appname.MY_RECEIVER_START";
private Radio radio;
In the service constructor
//Initiate our receiver
radio = new Radio();
//Activate our recevier
context.registerReceiver(radio, new IntentFilter(MY_RECEIVER_START));
Also in the service, create the receiver class and the method which shows toast
/**
* Receiver Class
* This setup checks for the incoming intent action to be able to
* attach more messages to one receiver.
*/
private class Radio extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(MY_RECEIVER_START)){
//show toast
}
}
}
After from anywhere in the application send message to our radio
context.sendBroadcast(new Intent("com.yourcompanyname.appname.MY_RECEIVER_START"));

addAction() & Service calling Dilemma

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 :)
}
}
};

registering receiver to filter that can not be found

Can u help me find out why the registration of broadcast receiver returns null?
this is the code:
ScoIntent = new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
sReceiver = new ScoReceiver(context, Tmp);
if (context.registerReceiver(sReceiver, ScoIntent) == null) {
Log("FBR.GetBlueConnect:Error", "Can not find receiver ACTION_CONNECTION_STATE_CHANGED");
HFS.DisplayText("Can not connect to Bluetooth Headset, Please Exit", true);
}
and this is the reciver:
class ScoReceiver extends BroadcastReceiver {
public ScoReceiver(Context mcontext, Tools t){
bContext = mcontext;
tools = t;
}
#Override
public void onReceive(Context context, Intent arg1) {
tools.Log("ScoReceiver:onReceive", "In");
//arg1 = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
String action = arg1.getAction();
tools.Log("ScoReceiver:onReceive", ">>> Bluetooth SCO state changed !!! ");
if(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
int status = arg1.getIntExtra(BluetoothHeadset.EXTRA_STATE, AudioManager.SCO_AUDIO_STATE_ERROR );
}
The javadocs say,
Returns the first sticky intent found that matches filter, or null if
there are none.
Does this receiver have a sticky intent? Here's a post that talks about the difference between a stick and non-sticky intent,
what is the difference between sendStickyBroadcast and sendBroadcast in Android

Categories

Resources