BroadCastReceiver Android - android

I'm realy newbie in android, and i'm having dificult with broadcastreceiver in my project.
I've created uses-permission and the receiver in AndroidManifest.xml, created the class but it not passing on the logcat message.
MY RECEIVER CLASS
package com.polifrete.polifreteFunctions;
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("Script", "Passou AQUI");
Intent i = new Intent(context, VerificaNovoFreteService.class);
context.startService(i);
}
}
MY ANDROIDMANIFEST.XML
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="com.polifrete.polifreteFunctions.MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
What i'm doing wrong? Please, help me!

Not every Phone sends the BOOT_COMPLETED Broadcast. For example, I think it was HTC, sends the QUICKBOOT_POWERON Broadcast, if it has boot up. Also your logcat is maybe not connected to your phone at Boot-Up-Time. I'd suggest to create a Toast to check, wether your Boot-Reciever is executed.
You can create this Toast with this code:
Toast toast = Toast.makeText(getApplicationContext(), "Boot-Reciever Started", Toast.LENGT_LONG);

#Felipe A., it's possible that you have a problems with CPU...The oficial documentation talks about it, and says the best use is WakefulBroadcastReceiver guarantee a that CPU will stays awake, you can read this post that talk about it: https://stackoverflow.com/a/26380942/3996257
This is my code with WakefulBroadcastReceiver:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntent_Service.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
The gcm receiver needs to add your package in your intent-filter it's the only difference with my code. And my receiver have this code:
<receiver
android:name=".App_Services.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />/>
<category android:name="your.package" />
</intent-filter>
</receiver>
It's possible your code don't recognizes your receiver because doesn't know their package. Tell me if I helps you, good luck!

Related

Do something when a headset is plugged in when my app is running in the background. (if possible i want to do it with broadcast receivers)

I want to do something when a headset is plugged in when my app is running in the background. (if possible I want to do it with a broadcast receiver)
I tried the code below:
--ReceiveBroadcast--
package com.example.openmusiconheadsetconnect;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class ReceiveBroadcast extends BroadcastReceiver {
public ReceiveBroadcast() {
}
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Received!",Toast.LENGTH_LONG).show();
}
}
--Manifest--
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.openmusiconheadsetconnect" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver
android:name=".ReceiveBroadcast"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" />
</intent-filter>
</receiver>
</application>
</manifest>
Thank you!
Your code is correct, but as far as I know, you cannot put the HEADSET_PLUG filter on the manifest.
Instead, create a receiver in its own class, and make it listen for USER_PRESENT (screen unlocked) or BOOT_COMPLETED in the manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<receiver android:name="classes.myReceiver" >
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
When triggered by such events, your receiver should start the service:
public class myReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
Intent service = new Intent(ctx, VoiceLaunchService.class);
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)||intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
ctx.startService(service);
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
ctx.stopService(service);
}
}
The service will now register the receiver that will be listening to the HEADSET_PLUG intent, in its onCreate method:
#Override
public void onCreate() {
super.onCreate();
speechReconRx=new SpeechReconControlReceiver(this);//"this" will allow you to call service's methods from the receiver
registerReceiver(speechReconRx, new IntentFilter(Intent.HEADSET_PLUG));
}
It's is a hassle, but you'll need it if you don't want to use an activity.
It is google's fault for not letting us put PLUG receivers in the manifest! Finally make the Broadcast that will take action when the headset is plugged in.
public class SpeechReconControlReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
Log.e("joshcsr","HEADSET PLUGGED!");
if(intent.getStringExtra("command")!=null){
c=intent.getStringExtra("command");
}
//run some methods from the service
if (c.equals("resume")) {
sService.resume();
}
if (c.equals("pause")) {
sService.pause();
}
if (c.equals("stop")) {
sService.stop();
}
}
}
To wrap, up you will need:
*A receiver for the BOOT/Screen unlock events.
*A Service to hold everything that will run on the background and to register your headset listening broadcast.
*And a receiver for the headset Plug, that will take action and call methods hosted in the service.
I've did this yesterday, and it works from Jelly bean to Lollipop ...and perhaps even older versions. Cheers.
First you'll need permission to start app in background after boot is completed.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
and also specify this in your broadcast receiver,
<receiver android:name=".YourBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
Then create a service that run your application in background, and inside the service use AudioManager.isWiredHeadsetOn() to check if the headset is plugged in. And if so, do the task you want.
while(AudioManager.isWiredHeadsetOn()){
//your task goes here
}
Also add the permission in manifest
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />

unable to run service when Date changes using broadcast receiver

I create an birthday reminder app. I want to start service at 12:00 in night to scan birthdays of person in Database. I add a broadcast receiver.
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.DATE_CHANGED"/>
</intent-filter>
</receiver>
But It don't work. I don't why..
here is the code of broadcast receiver .....
package com.example.forgetmenot;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Toast.makeText(arg0, "BroadCast Receiver", Toast.LENGTH_SHORT).show();
arg0.startService(new Intent("com.example.forgetmenot.BirthdayService"));
}
}
I wanna execute this code when date change. Please Help me. I need this to work to complete my app. thanks...
create receiver in Manifest
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.DATE_CHANGED" />
</intent-filter>
</receiver>
create BroadcastReceiver class
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
Log.e("", "ACTION_DATE_CHANGED received");
}
}
}
100% working

BroadcastReceiver is not working

I have implemented this broadcast reciever:
public class ServiceManager extends BroadcastReceiver {
private final String BOOT_ACTION = "android.intent.action.BOOT_COMPLETED";
private final String BOOT_ACTION_FIRST_LAUNCH = "android.intent.action.PACKAGE_FIRST_LAUNCH";
private final String BOOT_ACTION_RESTARTED = "android.intent.action.PACKAGE_RESTARTED";
#Override
public void onReceive(Context context, Intent intent) {
// All registered broadcasts are received by this
String action = intent.getAction();
if (action.equalsIgnoreCase(BOOT_ACTION) || action.equalsIgnoreCase(BOOT_ACTION_FIRST_LAUNCH) ||
action.equalsIgnoreCase(BOOT_ACTION_RESTARTED)) {
// TODO: Action
}
}
}
AndroidManifest.xml
<receiver android:name="package.service.ServiceManager" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.PACKAGE_FIRST_LAUNCH" />
<action android:name="android.intent.action.PACKAGE_RESTARTED" />
</intent-filter>
</receiver>
The BOOT_COMPLETED action is working right, but, the PACKAGE_FIRST_LAUNCH and PACKAGE_RESTARTED are not working. I need to launch my broadcast receiver when I launch my app, that's why I'm using these actions. But, when I launch or restart the app, the receiver is not working. It only works when I restart my mobile phone. Are there something wrong in my source?
FYI: PACKAGE_FIRST_LAUNCH is only sent to the installer package, i.e. whatever you used to install the application - for most end users that would be Android Market.
Edit:
Oh, and for "PACKAGE_RESTARTED", break that one out into its own <intent-filter> and add a
<data android:scheme="package"/>
since that one comes with an URI and an explicit scheme.
Logically it seems that PACKAGE_FIRST_LAUNCH will be broadcasted once your app is run for the first time after boot/reboot. And PACKAGE_RESTARTED should be broadcasted if your application activity stack is removed and then your app is clicked to start again (like restart).
However, you may simply achieve this by broadcasting a custom action string when ever your app is launched (perhaps from your first activity).
Manifest:
...
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></>
...
<receiver android:name=".AutoStart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
...
Receiver:
package YourPackage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AutoStart extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
// Your code
}
}
}
The intent android.intent.action.PACKAGE_FIRST_LAUNCH is introduced in Android API Level 12. If you are using lesser API Level it will not work. So change your project settings accordingly.

ACTION_SCREEN_ON and ACTION_SCREEN_OFF not working?

I'm trying to turn WiFi off when the screen is OFF (locked), and turn it on again when screen is ON (unlocked).
I made a BroadcastReceiver; put in manifest this code:
<receiver android:name="MyIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.USER_PRESENT" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
and this is the class MyIntentReceiver:
package org.androidpeople.boot;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyIntentReceiver extends BroadcastReceiver {
// Called when boot completes
public static boolean startup;
#Override
public void onReceive(Context context, Intent intent) {
// Set what activity should launch after boot completes
System.out.println("Intent Action: " + intent.getAction());
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
System.out.println("locked : ACTION_SCREEN_OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
System.out.println("not locked : ACTION_SCREEN_ON ");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
System.out.println("User Unlocking it ");
}
else if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
// this to indicate that program is running
// automaticlly not manually by user
startup = true;
System.out.println("Automatic BOOT at StartUp");
Intent startupBootIntent = new Intent(context, LaunchActivity.class);
startupBootIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startupBootIntent);
}
}
}
And the result is - both ACTION_SCREEN_ON
and ACTION_SCREEN_OFF never fired!
USER_PRESENT and BOOT_COMPLETED worked fine but the other did not. I'm using an emulator, not a real device - can this cause the problem?
Any help?
I need to catch the screen on and off in order to enable/disable WiFi
to save battery.
Thanks in advance
To capture the SCREEN_OFF and SCREEN_ON actions (and maybe others) you have to configure the BroadcastReceiver by code, not through the manifest.
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenStateBroadcastReceiver();
registerReceiver(mReceiver, intentFilter);
It's tested and works right.
You cannot catch those intents through XML (I forget why). However, you could use a Service that registers a BroadcastReceiver member in its onStartCommand() and unregisters it in its onDestroy(). This would require the service to be running in the background, constantly or as long as you need it to, so be sure to explore alternative routes.
You could define the BroadcastReceiver in your Service class like so:
private final class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//stuff
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
//other stuff
}
}
}
For a slightly complicated example, but one that shows how the BroadcastReceiver and Service interact see CheckForScreenBugAccelerometerService from my app, ElectricSleep.

Android BroadcastReceiver on startup - keep running when Activity is in Background

I'm monitoring incoming SMSs.
My app is working perfectly with a BroadcastReceiver. However it is working from an Activity and would like to keep the BroadcastReceiver running all the time (and not just when my Activity is running).
How can I achieve this? I've looked through the lifecycle of the BroadcastReceiver but all that is mentioned in the documentation is that the lifecycle is limited to the onReceive method, not the lifecycle of keeping the BroadcastReceiver checking for incoming SMS.
How can I make this persistent?
Thanks
You need to define a receiver in manifest with action name android.intent.action.BOOT_COMPLETED.
<!-- Start the Service if applicable on boot -->
<receiver android:name="com.prac.test.ServiceStarter">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Make sure also to include the completed boot permission.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Use Service for this to make anything persist. And use receivers to receive Boot Up events to restart the service again if system boots..
Code for Starting Service on boot up. Make Service do your work of checking sms or whatever you want. You need to do your work in MyPersistingService define it your self.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ServiceStarter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent("com.prac.test.MyPersistingService");
i.setClass(context, MyPersistingService.class);
context.startService(i);
}
}
Service or Boot Completed is not mandatory
In fact, you don't need to implement a Service or register to android.intent.action.BOOT_COMPLETED
Some examples shows how to register/unregister a BroadcastReceiver when activity is created and destroyed. However, this is useful for intents that you expect only when app is opened (for internal communication between Service/Activity for example).
However, in case of a SMS, you want to listen to the intent all the time (and not only when you app is opened).
There's another way
You can create a class which extends BroadcastReceiver and register to desired intents via AndroidManifest.xml. This way, the BroadcastReceiver will be indepedent from your Activity (and will not depend from Activity's Life Cycle)
This way, your BroadcastReceiver will be notified automatically by Android as soon as an SMS arrive even if your app is closed.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest>
...
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application>
....
<receiver android:name=".MyCustomBroadcastReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
MyCustomBroadcastReceiver.java
public class MyCustomBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent != null) {
String action = intent.getAction();
if(action != null) {
if(action.equals("android.provider.Telephony.SMS_RECEIVED")) {
// DO YOUR STUFF
} else if (action.equals("ANOTHER ACTION")) {
// DO ANOTHER STUFF
}
}
}
}
}
Notes
You can add others intent-filters to AndroidManifest and handle all of them in same BroadcastReceiver.
Start a Service only if you will perform a long task. You just need to display a notification or update some database, just use the code above.
Add Broadcast Reciever in manifest:
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
Create Class BootReciever.java
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
// +++ Do Operation Here +++
}
}
}
Beside #Javanator answer I would like to include a case for Android version of (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) In my case this is working for Android SDK 29 (10)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context,FloatingWindow.class));
} else {
context.startService(new Intent(context, FloatingWindow.class));
}
use this code and also mention the broadcast in Manifest also:
public class BootService extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
Toast.makeText(context, "Boot Completed", Toast.LENGTH_SHORT).show();
//write code here
}
}
}
I just want to mention that in case of some Chinese phone brands (e.g. MI), you need to go to Settings and give autostart permission to your app.
Otherwise the battery optimisation feature will kill your service in background and broadcast receiver will not work.
So you can redirect your user to Settings and ask them to give that permission.

Categories

Resources