BroadcastReceiver to notify when Bluetooth is connected - java

I want to make a BroadcastReceiver that notifies me when the Bluetooth is connected to another device.
BroadcastReceiver bluetooth = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED) {
Toast.makeText(MainActivity.this, "done!", Toast.LENGTH_LONG)
.show();
}
}
};
and
IntentFilter ff = new IntentFilter();
ff.addAction(android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED);
registerReceiver(bluetooth, ff);
and AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
but when the device is connected, nothing happens, why?

Try this way:
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
{
// LOG - Connected
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action))
{
// LOG - Disconnected
}
}
}
I hope it helps.

Related

Android SMS receiver call twice

I would like to notify the incoming sms message. I implemented the BroadcastReceiver for SMS receiver. And I also implemented the service for BOOT_COMPLETED action. Because the receiver cannot be registered if the device is reboot. When I launch the apps, that only call onReceiver once. But I reboot the device and start the BOOT_COMPLETED service. That will make the onReceive method call twice. But I don't know why. I confirm I only register the receiver once.
ps: When I reboot the device, I received the log order is enable receiver, register receiver, enable receive, onReceived, onReceived
Here is my code:
AutoStartService.java
public class AutoStartService extends Service {
private SmsReceiver smsReceiver;
public static boolean isStarted = false;
#Override
public void onCreate() {
super.onCreate();
isStarted = true;
if(!SmsReceiver.isEnableReceiver && smsReceiver == null) {
smsReceiver = new SmsReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, intentFilter);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Log.e("AAA", "register receiver");
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
isStarted = false;
Toast.makeText(this, "Service Destroy", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
BootCompleteReceiver.java
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(!AutoStartService.isStarted) {
new Handler().postDelayed(() -> {
Intent service = new Intent(context, AutoStartService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(service);
} else {
context.startService(service);
}
}, 500);
}
}
}
SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver implements SmsHelper.SmsHelperDelegate {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
public static boolean isEnableReceiver = false;
public SmsReceiver() {
super();
isEnableReceiver = true;
Log.e("AAA", "enable receiver");
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Log.e("SmsReceiver", "onReceived");
}
}
}
AndroidManifest.xml
<receiver android:name=".receiver.SmsReceiver" android:enabled="true" android:exported="true">
<intent-filter android:priority="2147483647">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<service android:name=".receiver.AutoStartService" android:exported="true"/>
<receiver android:name=".receiver.BootCompleteReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>

Android alarmManager, BroadcastReceiver onReceive never called

I'm trying to set up a alarm to start a job on a certain time but my alarm is never trigger and I don't understand what i'm missing. I'm using android api 22.
Thank you.
public class MainActivity extends ProtectedActivity {
#Override
public void onResume() {
super.onResume();
if (terminalSettings.GetSettlementEnabled())
{
startAlarmManager();
}
}
private void startAlarmManager()
{
Intent i = new Intent(MainActivity.this,
AlarmBroadcastReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0,
i, 0);
AlarmManager am =( AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, pi); //
Millisec * Second * Minute
}
}
class AlarmBroadcastReceiver
public class AlarmBroadcastReceiver extends BroadcastReceiver {
public AlarmBroadcastReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Alarm !!!!!!!!!!",
Toast.LENGTH_LONG).show(); // For example
}
}
In the manifest I added those line
<receiver android:name=".AlarmBroadcastReceiver"></receiver>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
You need to call registerReceiver
public static final String Broadcast_PLAY_NEW_AUDIO = "Some key so you know which broadcast is which";
//Create Receiver
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Do stuff
}
};
//Register receiver
IntentFilter filter = new IntentFilter(HomeActivity.Broadcast_PLAY_NEW_AUDIO);
registerReceiver(receiver, filter);
//Send Broadcast
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
sendBroadcast(broadcastIntent);

How to turn off the alarm?

My App goes like this:
When you first start the app, you'll see a button. Connecting or disconnecting the AC charger doesn't affect anything until you hit that Start button.
When you tap the Start button, the "service" is started.
Now if you remove the AC charger you will hear an alarm sound.
Connecting the AC with the device again should stop the alarm but it does NOT.
Now removing the AC again starts another alarm. The alarms overlap.
Can you help me find the bug?
Thanks
My work so far:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yousef.mustafa.antitheft">
<application
android:allowBackup="true"
android:icon="#mipmap/antitheft"
android:label="#string/app_name"
android:roundIcon="#mipmap/antitheft"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".PowerConnectionReceiver">
</receiver>
</application>
</manifest>
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button startServiceButton;
PowerConnectionReceiver powerConnectionReceiver;
BroadcastReceiver powerDisconnectedBroadcastReceiver;
BroadcastReceiver powerConnectedBroadcastReceiver;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
powerConnectionReceiver = new PowerConnectionReceiver(true);
startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);
powerDisconnectedBroadcastReceiver = new PowerConnectionReceiver(true);
powerConnectedBroadcastReceiver = new PowerConnectionReceiver(false);
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (startServiceButton.isActivated()) {
unregisterReceiver(powerDisconnectedBroadcastReceiver);
unregisterReceiver(powerConnectedBroadcastReceiver);
Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
startServiceButton.setActivated(false);
} else {
monitorBatteryChanges();
}
}
});
}
private void monitorBatteryChanges() {
IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
registerReceiver(powerDisconnectedBroadcastReceiver, powerDisconnectedIntentFilter);
IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
registerReceiver(powerConnectedBroadcastReceiver, powerConnectedIntentFilter);
Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
startServiceButton.setActivated(true);
}
}
PowerConnectionReceiver.java
public class PowerConnectionReceiver extends BroadcastReceiver {
MediaPlayer mediaPlayer = new MediaPlayer();
// Determine whether the AC is disconnected or not
private boolean POWER_DISCONNECTED = true;
PowerConnectionReceiver(boolean disconnected) {
this.POWER_DISCONNECTED = disconnected;
}
#Override
public void onReceive(Context context, Intent intent) {
if (POWER_DISCONNECTED) {
mediaPlayer = MediaPlayer.create(context, R.raw.alarm_2);
Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
mediaPlayer.setLooping(true);
//POWER_DISCONNECTED = false;
} else {
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The bug is in your complex code.
You register two different instances of PowerConnectionReceiver one for "connected" and another for "disconnected" events. So MediaPlayer is started in "connected" receiver, and you try to stop MediaPlayer in "disconected", but it doesn't play.
You should remove POWER_DISCONNECTED field, and handle event in a single instance of receiver. You can register a single receiver for multiple events and use intent.getAction() to check how to handle it.
UPD
Also you can make your receiver singleton, to prevent multiple registrations, and playing of multiple MediaPlayers
I was finally able to find a solution.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button startServiceButton;
BroadcastReceiver powerConnectionBroadcastReceiver;
IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);
powerConnectionBroadcastReceiver = new PowerConnectionBroadcastReceiver();
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (startServiceButton.isActivated()) {
unregisterReceiver(powerConnectionBroadcastReceiver);
startServiceButton.setActivated(false);
Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
} else {
monitorBatteryChanges();
}
}
});
}
private void monitorBatteryChanges() {
registerReceiver(powerConnectionBroadcastReceiver, powerDisconnectedIntentFilter);
registerReceiver(powerConnectionBroadcastReceiver, powerConnectedIntentFilter);
startServiceButton.setActivated(true);
Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
}
}
PowerConnectionBroadcastReceiver.java
public class PowerConnectionBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mediaPlayer;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
mediaPlayer = MediaPlayer.create(context, R.raw.alarm_1);
mediaPlayer.start();
mediaPlayer.setLooping(true);
Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
} else {
try {
if (mediaPlayer != null)
mediaPlayer.release();
Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
It may not be the best solution but it works :)
Thanks for the help.

Android Bluetooth Scanner Not Running as a Service

I'm trying to run bluetooth beacon scanner as a service, so when the application is not active, when beacon is detected, a notification can.
The Service Code (Java) :
public class BtService extends Service {
public static final String TAG = BtService.class.getSimpleName();
private ScanCallback mScanCallback;
private BluetoothAdapter btAdapter;
private BluetoothLeScanner btScanner;
private boolean mIsScanning = false;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "OnCreate Service");
final BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = btManager.getAdapter();
initBtCallBack();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "OnStartCommand Service");
btStartScanning();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Destroy");
btStopScanning();
}
/**
* BlueTooth CallBack
*/
private void initBtCallBack() {
Log.d(TAG, "InitBtCallBack");
try {
btScanner = btAdapter.getBluetoothLeScanner();
} catch (Exception e) {
e.printStackTrace();
}
mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
Log.i(TAG, "Something found : " + result.getDevice().getAddress());
BluetoothDevice device = result.getDevice();
Log.i(TAG, "btDevice : " + device.toString());
Log.i(TAG, "result : " + result.toString());
btUseBeacon(result);
}
};
}
private void btStartScanning() {
if (btScanner != null) {
if(! mIsScanning) {
Log.i(TAG, "START scanning...");
myBeacons.clear();
loadMyBeaconList();
mIsScanning = true;
btScanner.startScan(mScanCallback);
}
} else {
Log.i(TAG, "CANNOT START Scanning");
}
}
private void btStopScanning() {
if(mIsScanning) {
Log.i(TAG, "STOP scanning");
mIsScanning = false;
btScanner.stopScan(mScanCallback);
saveMyBeaconList();
}
}
}
There also a BroadcastReceiver Class to start the Service
public class BtStartServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, BtService.class);
context.startService(service);
}
}
Déclaration in the Manifest.xml, between the . Permission for Boot_Completed as also been added.
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<service
android:name=".BtService"
android:icon="#mipmap/ic_launcher"
android:enabled="true">
</service>
<receiver android:name=".BtStartServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
When the application is active or not, seems it does not work. In the logcat, I don't see any of the LOG i added in the code of the service.
When I kill the application, the logcat shows that the application is restarting, but nothing about Logs in code.
When I try to run this code adapted for an Activity, It works, beacon are detected and can make notification.
I don't wan't to use any beacon library or SDK, as I work with generic beacon.
Thank's for your help.

Android Broadcast receiver with multiple actions

How should I implement a broadcast receiver & filter so that it can response to multiple intents.
private BroadcastReceiver myReceiver;
IntentFilter myFilter = new IntentFilter();
onCreate():
myFilter.addAction("first");
myFilter.addAction("second");
myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do different actions according to the intent
}
};
registerReceiver(myReceiver, myFilter);
from my fragment:
Intent i = new Intent("first"); sendBroadcast(i);
Intent i = new Intent("second"); sendBroadcast(i);
Thanks
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action != null) {
if(action.equals("action1") {
// CODE
} else if (action.equals("action2") {
// CODE
}
}
}

Categories

Resources