Android Bluetooth Discovery not working - java

I am trying to list bluetooth devices available periodically. The idea is to run the startDiscovery() fuction every 4 secs and list the visible devices.
package com.neondude.cupid;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
Timer mTimer;
private ListView listView;
private ArrayList<String> mDeviceList = new ArrayList<String>();
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> BTArrayAdapter;
Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
BTArrayAdapter = new ArrayAdapter<String>(this,R.layout.list_view);
listView.setAdapter(BTArrayAdapter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
private void startTimer(){
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new Mytask(), 4000, 1000 * 5);
}
class Mytask extends TimerTask {
#Override
public void run(){
mHandler.post(new Runnable(){
#Override
public void run(){
find();
}
});
}
}
public void find(){
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
mBluetoothAdapter.startDiscovery();
}
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);
BTArrayAdapter.notifyDataSetChanged();
}
}
};
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
}
I have included the startDiscovery() function in the timertask handler. But when i do this , the devices and not listed in my listView.

You should check if the bluetooth is on, and ask the user to turn on if is off:
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else{
startTimer();
}
You could start the timer onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (resultCode == RESULT_OK) {
// The user turn on the bluetooth
startTimer();
}
}
}

The startTimer() function is never called, therefore the timerTask does not begin.

Related

Android App not responding after music service has started

I have an android app in which I have an activity and a service.
The service is supposed to play music and switch between four songs (depends on what button you press)
The problem is that a few minutes/seconds (it's not always at the same time) after you start the service by playing a song a notification pop ups which claims that the 'app has stopped responding' (with the option to wait and the option to exit). If you press the wait button the notification just goes away and the app and music continues the same. The notification will keep coming back though and unfortunately I am not sure why.
Should probably mention that this only happens to me when the service is on. I have tested this app many times. Never have a notification like that. Only when music is played.
My service:
package com.example.project25112021;
import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class MyService extends Service {
MediaPlayer mediaPlayer;
MediaPlayer mediaPlayer2;
MediaPlayer mediaPlayer3;
MediaPlayer mediaPlayer4;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.stronger);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
mediaPlayer2 = MediaPlayer.create(this, R.raw.silksonic);
mediaPlayer2.setLooping(true); // Set looping
mediaPlayer2.setVolume(100, 100);
mediaPlayer3 = MediaPlayer.create(this, R.raw.davidguetta);
mediaPlayer3.setLooping(true); // Set looping
mediaPlayer3.setVolume(100, 100);
mediaPlayer4 = MediaPlayer.create(this, R.raw.beatit);
mediaPlayer4.setLooping(true); // Set looping
mediaPlayer4.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
int number = intent.getIntExtra("key", 0);
mediaPlayer.start();
mediaPlayer2.start();
mediaPlayer3.start();
mediaPlayer4.start();
mediaPlayer.seekTo(0);
mediaPlayer2.seekTo(0);
mediaPlayer3.seekTo(0);
mediaPlayer4.seekTo(0);
mediaPlayer.pause();
mediaPlayer2.pause();
mediaPlayer3.pause();
mediaPlayer4.pause();
if (number == 0){
mediaPlayer.start();
}
if (number == 1){
mediaPlayer2.start();
}
if (number == 2){
mediaPlayer3.start();
}
if (number == 3){
mediaPlayer4.start();
}
return startId;
}
//public void onStart(Intent intent, int startId) { }
#Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public void onLowMemory() {
}
}
The activity in which you choose what song to play:
package com.example.project25112021;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class SettingsMain extends AppCompatActivity {
Button button;
Button song1;
Button song2;
Button song3;
Button song4;
ImageView album1;
ImageView album2;
ImageView album3;
ImageView album4;
Drawable drawable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_main);
drawable = CameraBackground.getInstance().getBitmap();
LinearLayout relative = (LinearLayout) findViewById(R.id.ButtonFinBack);
if(drawable!= null) {
relative.setBackgroundDrawable(drawable);
}
else
relative.setBackgroundResource(R.drawable.bacckga1);
button = findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SettingsMain.this, MainActivity.class);
startActivity(intent);
}
});
song1 = findViewById(R.id.song1);
song2 = findViewById(R.id.song2);
song3 = findViewById(R.id.song3);
song4 = findViewById(R.id.song4);
album1 = findViewById(R.id.album1);
album2 = findViewById(R.id.album2);
album3 = findViewById(R.id.album3);
album4 = findViewById(R.id.album4);
album1.setImageResource(R.drawable.kanye);
album2.setImageResource(R.drawable.silksonic);
album3.setImageResource(R.drawable.davidguetta);
album4.setImageResource(R.drawable.mjthriller);
song1.setText("Play");
song2.setText("Play");
song3.setText("Play");
song4.setText("Play");
song1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",0);
startService(intent);
}
});
song2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",1);
startService(intent);
}
});
song3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",2);
startService(intent);
}
});
song4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",3);
startService(intent);
}
});
}
}
Thanks

Android Bluetooth for discover devices, method Broadcast receiver is never called

i have problem with this code everything works but when i press scan button nothing happens why is that, i'm sure this code is right i follow Bluetooth Android Developer tutorial, Upon debug, I found that the onReceive method of BroadcastReceiver is never called. However, Bluetooth is enabled. What am I missing?
package com.example.bluetoothmaccounter;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button buttonON , buttonOFF, scanBt;
ListView deviceList;
ArrayList<String> arrayList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
int requestCodeForEnable = 1;
Intent btEnablingIntent;
Vibrator vibrator;
MediaPlayer mediaPlayer;
TextView textView2 ;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOFF = findViewById(R.id.bt_off);
buttonON = findViewById(R.id.bt_on);
scanBt = findViewById(R.id.bt_scan);
deviceList = findViewById(R.id.device_list);
btEnablingIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
mediaPlayer = MediaPlayer.create(this, R.raw.alarm);
textView2 = findViewById(R.id.textView2);
// /////////////////// Enable bluetooth ///////////////////////
buttonON.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), "this device not support bluetooth", Toast.LENGTH_SHORT).show();
} else {
if (!bluetoothAdapter.isEnabled()) {
startActivityForResult(btEnablingIntent, requestCodeForEnable);
}
}
}
});
// /////////////////// disable bluetooth ///////////////////////
buttonOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
Toast.makeText(getApplicationContext(), "bluetooth disable", Toast.LENGTH_SHORT).show();
}
}
});
// /////////////////// start scan ///////////////////////
scanBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
arrayList.clear();
if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), " bluetooth not Enabled", Toast.LENGTH_SHORT).show();
} else {
bluetoothAdapter.startDiscovery();
Toast.makeText(getApplicationContext(), "discover started", Toast.LENGTH_SHORT).show();
}
}
});
try {
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
textView2.setText("befoore receiver");
registerReceiver(receiver, intentFilter);
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
deviceList.setAdapter(arrayAdapter);
} catch (Exception e) {
textView2.setText("exeption" + e.getMessage());
}
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
textView2.setText("on receive 1");
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
textView2.setText("found");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
arrayList.add(device.getName() + device.getAddress());
String size = "size is " + arrayList.size();
textView2.setText(size);
arrayAdapter.notifyDataSetChanged();
if (arrayList.size() >= 1) {
Toast.makeText(getApplicationContext(), "There are :" + arrayList.size() + "person here ", Toast.LENGTH_LONG).show();
vibrator.vibrate(3 * 1000);
mediaPlayer.start();
}
//
}
}
};
#Override
protected void onDestroy () {
super.onDestroy();
// Don't forget to unregister the ACTION_FOUND receiver.
textView2.setText("destrrooooooy");
unregisterReceiver(receiver);
}
}
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
You need to add these two permissions in AndroidManifest.xml

NullPointerException when I try to test the implemented Bluetooth feature

I am trying to create an application which activates and deactivates Bluetooth, finds the paired Bluetooth devices and scans for discovered Bluetooth devices. I added the permissions to the AndroidManifest.xml. And everything seems to be ok. However when I debug the app on the device(Samsung Galaxy tab 3 Lite) I get NullPointerException and the application crashes. Do you have an idea what might cause the problem? Please find below my code and the exception stack trace.
package dyankov.mylibraryrecommender.MainActivities.GUI;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import dyankov.mylibraryrecommender.R;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AroundMeActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private Button turnOn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
turnOn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
turnOn = (Button)findViewById(R.id.turnOn);
turnOn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
And here is my Logcat file:
Caused by: java.lang.NullPointerException
at dyankov.mylibraryrecommender.MainActivities.GUI.AroundMeActivity.onCreate(AroundMeActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
The code on line 60 is:
turnOn.setOnClickListener(new OnClickListener() { ... }
            
put turnOn = (Button)findViewById(R.id.turnOn) and all your Button object initialization before turnOn.setEnabled(false);
You try to use button before you set value for it.
Try this code:
text = (TextView) findViewById(R.id.text);
turnOn = (Button)findViewById(R.id.turnOn);
if(myBluetoothAdapter == null) {
turnOn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
turnOn.setOnClickListener(new OnClickListener() {

bluetooth pairing with selected device

Here is my problem/question, probably a nooby one....
I have an activity where the app checks if the bluetooth is switched on, if not it displays a pop-up window with a button to activate it.
when activated there is a button which will search for bluetooth devices.
now my question is how can i pair to the selected device which will be protected with an password, if it is already paired just connect to it (witouth entering the password again)
after connecting to the device it should go to the next page.
Here is my Code
package com.example.silcamanager96x32;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
public class Bluetooth_check extends Activity {
//global variables
private final static int REQUEST_ENABLE_BT = 1;
private ArrayAdapter<String> btArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_check);
btn_go();
btn_scan();
}
//tijdelijke button volgende pagina
public void btn_go(){
Button btn_go=(Button)findViewById(R.id.Button01);
btn_go.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("clicks","You Clicked B1");
Intent i=new Intent(
Bluetooth_check.this,
home.class);
startActivity(i);
}
});
}
//button scannen naar bluetooth apparaten en in ene lijst plaatsen
public void btn_scan(){
final Button scanb = (Button)findViewById(R.id.button);
final ListView Deviceslist = (ListView)findViewById(R.id.listView1);
btArrayAdapter = new ArrayAdapter<String>(Bluetooth_check.this, android.R.layout.simple_list_item_1);
Deviceslist.setAdapter(btArrayAdapter);
//vraagt of app bluetooth mag inschakelen
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(Bluetooth_check.this, "Your device doesnot support Bluetooth", Toast.LENGTH_LONG).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//onclick scan button
scanb.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
btArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
Toast.makeText(Bluetooth_check.this, "Scanning Devices", Toast.LENGTH_LONG).show();
}
});
Deviceslist.setOnItemClickListener( new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position,
long id) {
// onclick item gevonden apparaten
AlertDialog.Builder adb = new AlertDialog.Builder(
Bluetooth_check.this);
adb.setTitle("ListView OnClick");
adb.setMessage("Selected Item is = "
+ Deviceslist.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
adb.show();
}
});
registerReceiver(FoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(FoundReceiver);
}
private final BroadcastReceiver FoundReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
btArrayAdapter.add(device.getName() + "\n" + device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}};
}
try this link here is whole code ...Android + Pair devices via bluetooth programmatically and add permission to manifest
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />

how to set alarm when screen is off for android device?

Hi I want to set alarm notification when the mobile screen is off. My code is'
package com.my.timeout;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
public class ScreenON_OFF_ACTIVITY extends Activity
{
AlarmManager am;
private static final int REQUEST_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
onCreate1();
}
public void onCreate1() {
// initialize receiver
System.out.println("onCreate1 ");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
System.out.println("onCreate ");
}
#Override
protected void onPause() {
// when the screen is about to turn off
if (ScreenReceiver.screenOff) {
// this is the case when onPause() is called by the system due to a screen state change
System.out.println("SCREEN TURNED OFF");
} else {
// this is when onPause() is called when the screen state has not changed
System.out.println("this is when onPause() is called when the screen state has not changed ");
display_alarm();
}
super.onPause();
}
#Override
protected void onResume() {
// only when screen turns on
if (!ScreenReceiver.screenOff) {
// this is when onResume() is called due to a screen state change
System.out.println("SCREEN TURNED ON");
} else {
// this is when onResume() is called when the screen state has not changed
System.out.println(" this is when onResume() is called when the screen state has not changed ");
}
super.onResume();
}
}
ScreenReceiver.java
package com.my.timeout;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ScreenReceiver extends BroadcastReceiver
{
public static boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("onReceive ");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
System.out.println("SCREEN TURNED OFF on BroadcastReceiver");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
System.out.println("SCREEN TURNED ON on BroadcastReceiver");
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
UpdateService.java
package com.my.timeout;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
public class UpdateService extends Service {
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
System.out.println("Screen is off");
} else {
System.out.println("Screen is on");
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Now i want to set alarm when the screen has been go off. How can i do this.Can anybody tell me? thanks in advance.

Categories

Resources