Recording phone calls on Android - android

I am trying out the record outgoing call using mic written this code but not working, I tested the code for simple audio record it works fine, I am not sure when to start media record I putted start in broadcast receiver may be problem is there.
Here Audiorecoder is another class is created where I have implemented MediaRecoder
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
audrec = new AudioRecorder("newcall");
this.context = context;
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_DIAL))
{
try {
audrec.start();
recordstarted = 1;
telManager= (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
final PhoneStateListener phoneListener = new PhoneStateListener()
{
#Override
public void onCallStateChanged(final int state, final String incomingNumber)
{
getTelephonyOverview(telManager);
}
};
telManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
public void getTelephonyOverview(final TelephonyManager telManager)
{
int callState = telManager.getCallState();
switch (callState)
{
case TelephonyManager.CALL_STATE_IDLE:
{
if (recordstarted==1)
{
try {
audrec.stop();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recordstarted =0;
}
break;
}
case TelephonyManager.CALL_STATE_OFFHOOK:
{
try {
audrec.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recordstarted =1;
break;
}
case TelephonyManager.CALL_STATE_RINGING:
{
try {
audrec.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recordstarted =1;
break;
}
}
}
Another Code that i am trying out that create 3Gp file but not playing
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class androidrec extends Activity
{
Button btn_start;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); setContentView(R.layout.main);
btn_start = (Button) findViewById(R.id.btn_start);
UpdateRecorderState();
btn_start.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Toast.makeText(getBaseContext(),"Please enter both phone number and message.",
// Toast.LENGTH_SHORT).show();
if(!SharedData._Started) { StartServicesAtStartUp.Start_CallRec(getBaseContext()); }
else { StartServicesAtStartUp.Stop_CallRec(getBaseContext()); }
UpdateRecorderState();
}
});
}
private void UpdateRecorderState()
{
if(SharedData._Started)
{btn_start.setText("Stop Recording");}
else
{btn_start.setText("Start Recording");}
}
}[/code]
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.media.MediaRecorder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
//import com.lumitrend.netlogger.Logger;
public class CallStateListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber)
{
super.onCallStateChanged(state, incomingNumber);
switch(state)
{
case TelephonyManager.CALL_STATE_IDLE:
if(SharedData._Recording)
{ Recorders_Stop(); }
break;
case TelephonyManager.CALL_STATE_RINGING:
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
String CallDate = SanityDate();
String CallNum = SanityNum(incomingNumber);
String RootDir = SharedData._Path ;
String CallDir = SharedData._Path + CallNum + "/" ;
String CallFile = SharedData._Path + CallNum + "/" + CallNum + CallDate ;
if(!SharedData._Recording)
{
SharedData._Recording = true;
String med_state = android.os.Environment.getExternalStorageState();
if(!med_state.equals(android.os.Environment.MEDIA_MOUNTED))
{ break; }
File directory = null;
directory = new File(RootDir + "text.txt" ).getParentFile();
if (!directory.exists() && !directory.mkdirs())
{ break; }
directory = new File(CallDir + "text.txt" ).getParentFile();
if (!directory.exists() && !directory.mkdirs())
{ break; }
Recoders_Init(CallFile);
Recorder_Prepare();
}
Log.v("DEBUG", TelephonyManager.CALL_STATE_OFFHOOK + " ITS.CallRecorder - Recording Started " + state);
break;
}
}
private String SanityDate() {
SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd-HHmmss");
Date currentTime_1 = new Date();
return formatter.format(currentTime_1);
}
private void Recorders_Stop() {
try {
SharedData._recorder.stop(); SharedData._recorder.reset();
//SharedData._recorder_down.stop(); SharedData._recorder_down.reset();
//SharedData._recorder_up.stop(); SharedData._recorder_up.reset();
}
catch (IllegalStateException e) {}
SharedData._Recording = false;
}
private void Recorder_Prepare() {
try {
SharedData._recorder.prepare(); SharedData._recorder.start();
//SharedData._recorder_down.prepare(); SharedData._recorder_down.start();
//SharedData._recorder_up.prepare(); SharedData._recorder_up.start();
}
catch (IllegalStateException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
private void Recoders_Init(String path) {
String _ext = ".3gp";
int out_format = MediaRecorder.OutputFormat.THREE_GPP;
SharedData._recorder.setAudioSource(SharedData._Rec_Type);
SharedData._recorder.setOutputFormat(out_format);
SharedData._recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
SharedData._recorder.setOutputFile(path + "both" + _ext);
/*
SharedData._recorder_down.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK);
SharedData._recorder_down.setOutputFormat(out_format);
SharedData._recorder_down.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
SharedData._recorder_down.setOutputFile(path + "-down" + _ext);
SharedData._recorder_up.setAudioSource(MediaRecorder.AudioSource.VOICE_UPLINK);
SharedData._recorder_up.setOutputFormat(out_format);
SharedData._recorder_up.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
SharedData._recorder_up.setOutputFile(path + "-up" + _ext);
*/
}
private String SanityNum(String numstr)
{
String out = "";
for(char ch : numstr.toCharArray())
{
switch(ch)
{
case ' ':
break;
case '~':
break;
case '!':
break;
case '#':
break;
case '#':
break;
case '$':
break;
case '%':
break;
case '^':
break;
case '&':
break;
case '*':
break;
case '(':
break;
case ')':
break;
case '-':
break;
case '_':
break;
case '=':
break;
case '|':
break;
default:
out = out + ch;
}
}
return out;
}
}
import android.media.MediaRecorder;
final public class SharedData
{
static int _Rec_Type = android.media.MediaRecorder.AudioSource.VOICE_CALL;
static String _Path = android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + "/ITS-CallRecorder/";
static boolean _Started = false;
static boolean _AutoStart = true;
static boolean _Recording = false;
static MediaRecorder _recorder = new MediaRecorder();
static MediaRecorder _recorder_down = new MediaRecorder();
static MediaRecorder _recorder_up = new MediaRecorder();
SharedData() { }
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class StartServicesAtStartUp extends BroadcastReceiver
{
public static Intent phoneStateListener;
public void onReceive(Context context, Intent intent)
{
Log.d("DEBUG", "com.its.CallRecorder Initiated ...");
Start_CallRec(context);
}
public static void Start_CallRec(Context context)
{
if(!SharedData._Started )
{
if(SharedData._AutoStart)
{
phoneStateListener = new Intent(context, CallStateListener.class);
phoneStateListener.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(phoneStateListener);
Log.d("DEBUG", "com.its.CallRecorder Call Recorder Started ...");
TelephonyManager tManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
CallStateListener callStateListener = new CallStateListener();
tManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);
SharedData._Started = true;
Toast.makeText(context," Call Recording Started ... ", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(context," Call Recording Already Active.. ", Toast.LENGTH_SHORT).show();
}
}
public static void Stop_CallRec(Context context)
{
if(SharedData._Started )
{
context.stopService(phoneStateListener);
Toast.makeText(context," Call Recording Stopped ... ", Toast.LENGTH_SHORT).show();
SharedData._Started = false;
}
else
{
Toast.makeText(context," Call Recording Already Stopped ... ", Toast.LENGTH_SHORT).show();
}
}
}

You cannot record calls because the firmware doesn't support it . There is a better answer at xda-devs which I got from android's open issues list :
The voice streams were handled by the baseband processor
baseband processor, it's that the
baseband firmware aren't setup to
offer the streams to the application
processor that's limiting the ability
to truly record a call. The Android
system long has the API implemented,
but it can do nothing in this case.
Since the baseband firmware is close
sourced and available in binary only,
I doubt if the brilliant hackers here
can do anything about this.
someone found a "cure" for HD2 , just
by editing the registry -
xda-developers.com/windows-mobile/two-way-in-call-recording-on-hd2-fixed/wo-way-in-call-recording-on-hd2-fixed/

Call recording is not yet possible on Android. See this feature request.
You can record your voice from microphone, but you can not record the sound of the other party. If you only want to record your voice use android.media.MediaRecorder.AudioSource.MIC

Related

Using android.hardware.usb in Flutter application

I have tried using plugins available:
flutter_android
This includes:
Sensor
SensorEvent
SensorEventListener
SensorManager
usb_serial
So i need to talk to usb devices however the plugin usb_serial
does not meet my needs since i need to use more than the package provides.
Basically i either need to create my own plugin or i need to find a way to expose the native android.hardware.usb to flutter.
Need help i don't know what is best or how to do either.
This was a long time ago but will try to help as best as possible
Since I was not able to find anything that met my needs I needed to create my own plugin using these
import com.ftdi.j2xx.D2xxManager;
import com.ftdi.j2xx.FT_Device;
My MainActivity look like this
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.ftdi.j2xx.D2xxManager;
import com.ftdi.j2xx.FT_Device;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
private static final String TAG = "D2XX";
private static final String CHANNEL = "bridge";
private static final String EVENT_CHANNEL = "event";
private static final String INPUT_EVENT_CHANNEL = "input";
private D2xxManager m_deviceManager = null;
private FT_Device m_connectedDevice;
private CONTROLLER_ENUMS m_CONTROLLER_STATUS = CONTROLLER_ENUMS.Closed;
private int m_iDeviceCount = 0;
private List<D2xxManager.FtDeviceInfoListNode> mDeviceInfoListNode;
private CountDownTimer m_updateTimer;
private final String m_initialBitMask = "00111100";
private boolean m_input1State = false;
private boolean m_input2State = false;
private boolean m_output1State = false;
private boolean m_output2State = false;
private static boolean bRegisterBroadcast = true;
private long timeLeftInMilliseconds;
private boolean m_MountedState = false;
boolean isRunning = false;
private enum CONTROLLER_ENUMS {
OK,
Opened,
Closed,
Failed,
}
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler((call, result) -> {
String strCallName = call.method.toUpperCase();
switch (strCallName) {
case "INITIALIZE": {
m_CONTROLLER_STATUS = CONTROLLER_ENUMS.OK;
boolean bConnected = Initialise();
result.success(bConnected);
}
break;
case "GETDEVICE": {
JSONObject retVal = GetDeviceList();
if (retVal != null) {
result.success(retVal.toString());
}
}
break;
case "CONNECTDEVICE": {
try {
String strSerialNumber = call.argument("SerialNumber");
if (m_connectedDevice == null) {
boolean bConnected = ConnectToDevice(strSerialNumber);
result.success(bConnected);
} else {
result.success(true);
}
} catch (Exception e) {
Log.e(TAG, "CONNECT TO DEVICE ANDROID EXC: ", e);
}
}
break;
case "SETOUTPUT": {
int output = (int) call.argument("outputNumber");
boolean state = (boolean) call.argument("state");
SetOutputs(output, state);
}
break;
case "GETINPUT": {
JSONObject retVal = CheckDeviceInputs();
if (retVal != null) {
result.success(retVal.toString());
}
}
break;
default:
break;
}
});
new EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), EVENT_CHANNEL).setStreamHandler(
new EventChannel.StreamHandler() {
private BroadcastReceiver usbStateChangeReceiver;
#Override
public void onListen(Object arguments, EventChannel.EventSink events) {
usbStateChangeReceiver = createUSBStateChangeReceiver(events);
IntentFilter filter = new IntentFilter();
filter.addAction("android.hardware.usb.action.USB_DEVICE_ATTACHED");
filter.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED");
registerReceiver(
usbStateChangeReceiver, filter);
}
#Override
public void onCancel(Object arguments) {
unregisterReceiver(usbStateChangeReceiver);
usbStateChangeReceiver = null;
}
}
);
new EventChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), INPUT_EVENT_CHANNEL).setStreamHandler(
new EventChannel.StreamHandler() {
#Override
public void onListen(Object arguments, EventChannel.EventSink events) {
timeLeftInMilliseconds = 30000;
//timer is started when device is connected so tha android knows when to tell flutter button has
//been pressed
m_updateTimer = new CountDownTimer(timeLeftInMilliseconds, 100) {
public void onTick(long millisUntilFinished) {
isRunning = true;
JSONObject retVal = CheckDeviceInputs();
if (retVal != null) {
events.success(retVal.toString());
} else {
events.success(null);
}
}
public void onFinish() {
isRunning = false;
m_updateTimer.start();
}
}.start();
}
#Override
public void onCancel(Object arguments) {
//when event channel is closed we stop the timer then remove the method
if (m_updateTimer != null) {
isRunning = false;
m_updateTimer.cancel();
}
Log.w(TAG, "cancelling listener");
}
}
);
}
private BroadcastReceiver createUSBStateChangeReceiver(EventChannel.EventSink events) {
return new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//watches if the usb has been plugged in or not
String action = intent.getAction();
if ("android.hardware.usb.action.USB_DEVICE_DETACHED".equals(action)) {
Log.i(TAG, "Detached: ");
Toast.makeText(context, "Device detached",
Toast.LENGTH_LONG).show();
//if device usb plugs out cancel timer
m_connectedDevice = null;
events.success(false);
} else if ("android.hardware.usb.action.USB_DEVICE_ATTACHED".equals(action)) {
Log.i(TAG, "Attached:");
Toast.makeText(context, "Device attached",
Toast.LENGTH_LONG).show();
if (m_updateTimer != null) {
Log.e(TAG, "START THE TIMER: ");
m_updateTimer.start();
}
events.success(true);
}
}
};
}
// INITIALISE
private boolean Initialise() {
try {
m_deviceManager = D2xxManager.getInstance(this);
return m_deviceManager != null;
} catch (D2xxManager.D2xxException exc) {
Log.e(TAG, "Initialise: Failed to get instance");
return false;
}
}
// GET ALL CONNECTED DEVICES
private JSONObject GetDeviceList() {
// first check if the list is empty, then create the list based on what is plugged in
// for now only the first device will be connect
try {
m_iDeviceCount = m_deviceManager.createDeviceInfoList(this);
if (m_iDeviceCount == 0)
return null;
D2xxManager.FtDeviceInfoListNode firstItem = m_deviceManager.getDeviceInfoListDetail(0);
JSONObject returnData = new JSONObject();
try {
//create connected device info object to send to flutter
returnData.put("ID", firstItem.id);
returnData.put("Description", firstItem.description);
returnData.put("BCDDevice", firstItem.bcdDevice);
returnData.put("LineStatus", firstItem.lineStatus);
returnData.put("ModemStatus", firstItem.modemStatus);
returnData.put("Type", firstItem.type);
returnData.put("SerialNumber", firstItem.serialNumber);
return returnData;
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "GetDeviceList: Failed" + e);
return null;
}
} catch (Exception exc) {
Log.e(TAG, "GetDeviceList: Failed" + exc);
return null;
}
}
// CONNECT THE DEVICE
private boolean ConnectToDevice(String strSerialNumber) {
try {
m_connectedDevice = m_deviceManager.openBySerialNumber(this, strSerialNumber);
//m_initialBitMask
if (m_connectedDevice != null && m_connectedDevice.isOpen()) {
//printing the device details
Log.i(TAG, "ConnectToDevice: IsOpen : ");
Log.i(TAG, "ConnectToDevice: IsOpen : " + m_connectedDevice.getDeviceInfo().serialNumber);
Log.i(TAG, "ConnectToDevice: description : " + m_connectedDevice.getDeviceInfo().description);
Log.i(TAG, "ConnectToDevice: serialNumber : " + m_connectedDevice.getDeviceInfo().serialNumber);
Log.i(TAG, "ConnectToDevice: bcdDevice : " + String.valueOf(m_connectedDevice.getDeviceInfo().bcdDevice));
//setting bit mode
m_connectedDevice.setBitMode(Byte.parseByte(m_initialBitMask, 2), D2xxManager.FT_BITMODE_CBUS_BITBANG);
return true;
} else {
m_CONTROLLER_STATUS = CONTROLLER_ENUMS.Closed;
return false;
}
} catch (Exception exc) {
m_CONTROLLER_STATUS = CONTROLLER_ENUMS.Failed;
Log.e(TAG, "ConnectToDevice: Failed" + exc);
Log.i(TAG, "ConnectToDevice: IsNotOpen");
return false;
}
}
// SET OUTPUTS TO DEVICE
private void SetOutputs(int outputNumber, boolean bState) {
//if device is connected you can use this to activate relays
if (m_connectedDevice != null && m_connectedDevice.isOpen()) {
byte lByteMask = m_connectedDevice.getBitMode();
switch (outputNumber) {
//relay 1
case 1: {
if (bState) {
lByteMask |= 1;
} else {
lByteMask &= 0xFE;
}
}
break;
//relay 2
case 2: {
if (bState) {
lByteMask |= 2;
} else {
lByteMask &= 0xFD;
}
}
break;
}
//fire with new values
m_connectedDevice.setBitMode(lByteMask, D2xxManager.FT_BITMODE_CBUS_BITBANG);
}
}
// READ INTERRUPTS - Timer based
private JSONObject CheckDeviceInputs() {
JSONObject returnData = new JSONObject();
try {
if (m_connectedDevice != null && m_connectedDevice.isOpen()) {
byte inputBytes = m_connectedDevice.getBitMode();
boolean input1 = (inputBytes & 0x04) != 0x04;
boolean input2 = (inputBytes & 0x08) != 0x08;
if (input1) {
m_input1State = true;
}
if (input2) {
m_input2State = true;
}
//if input is true global will be set above then below if the local is
//not true anymore it will activate and deactivate the relays
if (!input1 && m_input1State) {
SetOutputs(2, true);
try {
//delay so relay light is seen
Thread.sleep(200);
SetOutputs(2, false);
} catch (InterruptedException ex) {
Log.e(TAG, "Set time out: ", ex);
}
m_input1State = false;
}
if (!input2 && m_input2State) {
SetOutputs(1, true);
try {
//delay so relay light is seen
Thread.sleep(200);
SetOutputs(1, false);
} catch (InterruptedException ex) {
Log.e(TAG, "Set time out: ", ex);
}
m_input2State = false;
}
returnData.put("Input1State", input1);
returnData.put("Input2State", input2);
return returnData;
} else {
return null;
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "Failed to get DeviceStatus: Failed" + e);
return null;
}
}
}
On my flutter side I create a banner that listens to the I/O
import 'dart:convert';
import 'package:covidqa/Controllers/DeviceController.dart';
import 'package:covidqa/Models/IRelayDevice.dart';
import 'package:covidqa/Models/Inputs.dart';
import 'package:covidqa/StateHandler/globals.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'package:provider/provider.dart';
class BannerView extends StatefulWidget {
final Function(Inputs) returningInputs;
final Function(bool) connected;
BannerView(this.returningInputs, this.connected);
#override
BannerViewState createState() {
return BannerViewState();
}
}
class BannerViewState extends State<BannerView> {
DeviceController deviceController = new DeviceController();
EventChannel eventChannel = const EventChannel('event');
EventChannel inputEventChannel = const EventChannel('input');
bool init;
IRelayDevice device;
Inputs inputs;
String error;
bool hasDevice = false;
Globals globals;
bool connected = false;
bool inputState1 = false;
bool inputState2 = false;
bool outputState1 = false;
bool outputState2 = false;
_init() {
deviceController.init().then((value) {
if (value == true) {
getDevice();
}
});
}
Future<void> getDevice() async {
if (!mounted) {
return;
}
deviceController.getDevice().then((data) => setState(() {
device = data;
connectDevice();
}));
}
Future connectDevice() async {
if (!mounted) {
return;
}
if (device != null) {
deviceController.connectDevice(device).then((data) => setState(() {
widget.connected(data);
connected = data;
if (data) {
inputEventChannel
.receiveBroadcastStream()
.listen(_onInput, onError: deviceController.onError);
}
}));
} else {
getDevice();
}
}
#override
void initState() {
super.initState();
_init();
eventChannel
.receiveBroadcastStream()
.listen(_onEvent, onError: deviceController.onError);
}
void _onEvent(Object event) {
if (!mounted) {
widget.connected(false);
device = null;
connected = false;
return;
}
setState(() {
hasDevice = event;
if (!hasDevice) {
device = null;
connected = false;
widget.connected(false);
} else {
connectDevice();
}
});
}
void _onInput(Object event) {
try {
if (!mounted) {
return;
}
if (event == null) {
print("Result is null");
return;
}
Map bodyResult = jsonDecode(event);
inputs = Inputs.fromJson(bodyResult);
widget.returningInputs(inputs);
} on PlatformException catch (e) {
print("exception" + e.toString());
}
}
#override
Widget build(BuildContext context) {
globals = Provider.of<Globals>(context);
return Container(
color: connected ? Colors.green : Colors.red,
height: MediaQuery.of(context).size.height * 0.01,
);
}
}
Again this was long ago and cant remember much and the code is not the most tidy but this is the just of it good luck

onScannerClosedWithResult(no.nordicsemi.android.beacon.Beacon)' on a null object reference

I am trying to write a app which scans for beacons,
when I login to the app, it starts scanning but after some seconds it just crashes. if I turn off my bluetooth it works fine. this is the error I get:
Process: com.noxel.apppaneladmintry2, PID: 11192
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.niloofar.showroom.BeaconsFragment.onScannerClosed()' on a null object reference
at com.example.niloofar.showroom.BeaconScannerFragment.onCancel(BeaconScannerFragment.java:56)
at android.app.Dialog$ListenersHandler.handleMessage(Dialog.java:1260)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:921)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:716)
and this is my code,
package com.example.niloofar.showroom;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.UUID;
import no.nordicsemi.android.beacon.Beacon;
import no.nordicsemi.android.beacon.BeaconRegion;
import no.nordicsemi.android.beacon.BeaconServiceConnection;
import no.nordicsemi.android.beacon.Proximity;
import no.nordicsemi.android.beacon.ServiceProxy;
public class drawermenu extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, BeaconServiceConnection.BeaconsListener, BeaconServiceConnection.RegionListener {
public ProfileFragment profileFragment;
private static final String SCANNER_FRAGMENT = "scannerFragment";
public static final String NRF_BEACON_SERVICE_URL = "market://details?id=no.nordicsemi.android.beacon.service";
public static final String OPENED_FROM_LAUNCHER = "no.nordicsemi.android.nrfbeacon.extra.opened_from_launcher";
public static final String EXTRA_OPEN_DFU = "no.nordicsemi.android.nrfbeacon.extra.open_dfu";
public static final int BEACON_COMPANY_ID = 0x0059;
private static final int REQUEST_ENABLE_BT = 1;
private boolean mServiceConnected;
private boolean mFragmentResumed;
private DatabaseHelper mDatabaseHelper;
private BeaconAdapter mAdapter;
private BeaconScannerFragment mScannerFragment;
int minor;
public Fragment fragment=null;
public FragmentA fragmentA;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(this, "Device dows not support Bluetooth", Toast.LENGTH_LONG);
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
mDatabaseHelper = new DatabaseHelper(this);
getSupportActionBar().setElevation(0);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}catch (Exception ex) {
Log.d("ERROR", ex.getMessage());
}
}
#Override
public void onStart() {
super.onStart();
// final Cursor cursor = mDatabaseHelper.getAllRegions();
bindService();
}
#Override
public void onResume() {
super.onResume();
// startScanning();
if (mFragmentResumed)
return;
mFragmentResumed = true;
// bindService();
onAddOrEditRegion();
}
#Override
public void onPause() {
super.onPause();
// stopScanning();
if (!mFragmentResumed)
return;
mFragmentResumed = false;
unbindService();
}
private BeaconServiceConnection mServiceConnection = new BeaconServiceConnection() {
#Override
public void onServiceConnected() {
try {
mServiceConnected = true;
final BeaconScannerFragment scannerFragment = mScannerFragment;
if (scannerFragment != null) {
startRangingBeaconsInRegion(BEACON_COMPANY_ID, BeaconRegion.ANY_UUID, scannerFragment);
} else {
// final FragmentManager fm = getChildFragmentManager();
// if (fm.getBackStackEntryCount() == 0) {
// Start scan only if there is no any other fragment (Mona Lisa) open
startScanning();
// }
}
} catch (Exception ex) {
Log.d("ERROR", ex.getMessage());
}
}
#Override
public void onServiceDisconnected() {
try {
mServiceConnected = false;
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
};
public void onAddOrEditRegion() {
// if (!ensurePermission())
// return;
try {
stopScanning();
// mScannerFragment=null;
final BeaconScannerFragment fragment = mScannerFragment = new BeaconScannerFragment();
fragment.show(getSupportFragmentManager(), SCANNER_FRAGMENT);
// fragment.isHidden();
mServiceConnection.startRangingBeaconsInRegion(BEACON_COMPANY_ID, BeaconRegion.ANY_UUID, fragment);
}
catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void startScanning() {
try {
if (mServiceConnected) {
startScanning(mServiceConnection);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void stopScanning() {
try {
if (mServiceConnected) {
stopScanning(mServiceConnection);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
private void bindService() {
// if (!ensurePermission())
// return;
try {
final boolean success = ServiceProxy.bindService(this, mServiceConnection);
if (!success) {
new AlertDialog.Builder(this).setTitle(R.string.service_required_title).setMessage(R.string.service_required_message)
.setPositiveButton(R.string.service_required_store, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, final int which) {
final Intent playIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(MainActivity.NRF_BEACON_SERVICE_URL));
startActivity(playIntent);
}
}).setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(final DialogInterface dialog) {
dialog.dismiss();
finish();
}
}).show();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
private void unbindService() {
try {
if (mServiceConnected) {
// Unbinding service will stop all active scanning listeners
ServiceProxy.unbindService(this, mServiceConnection);
mDatabaseHelper.resetSignalStrength();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void startScanning(final BeaconServiceConnection serviceConnection) {
try {
final Cursor cursor = mDatabaseHelper.getAllRegions();
while (cursor.moveToNext()) {
final UUID uuid = UUID.fromString(cursor.getString(2 /* UUID */));
final int major = cursor.getInt(3 /* MAJOR */);
final int minor = cursor.getInt(4 /* MINOR */);
final int event = cursor.getInt(6 /* EVENT */);
// We must start ranging for all beacons
serviceConnection.startRangingBeaconsInRegion(BEACON_COMPANY_ID, uuid, major, minor, this);
// And additionally start monitoring only for those with these two events set
if (event == BeaconContract.EVENT_IN_RANGE || event == BeaconContract.EVENT_OUT_OF_RANGE)
serviceConnection.startMonitoringForRegion(BEACON_COMPANY_ID, uuid, major, minor, this);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void stopScanning(final BeaconServiceConnection serviceConnection) {
try {
if (serviceConnection != null) {
serviceConnection.stopMonitoringForRegion(this);
serviceConnection.stopRangingBeaconsInRegion(this);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
#Override
public void onBeaconsInRegion(final Beacon[] beacons, final BeaconRegion region) {
try {
if (beacons.length > 0) {
final Cursor cursor = mDatabaseHelper.findRegion(region);
try {
if (cursor.moveToNext()) {
// Check and fire events
final int event = cursor.getInt(6 /* EVENT */);
for (final Beacon beacon : beacons) {
if (event == BeaconContract.EVENT_ON_TOUCH && Proximity.IMMEDIATE.equals(beacon.getProximity()) && Proximity.NEAR.equals(beacon.getPreviousProximity())) {
fireEvent(cursor);
break;
}
if (event == BeaconContract.EVENT_GET_NEAR && Proximity.NEAR.equals(beacon.getProximity()) && Proximity.FAR.equals(beacon.getPreviousProximity())) {
fireEvent(cursor);
break;
}
}
// Update signal strength in the database
float accuracy = 5;
for (final Beacon beacon : beacons)
if (Proximity.UNKNOWN != beacon.getProximity() && beacon.getAccuracy() < accuracy)
accuracy = beacon.getAccuracy();
accuracy = -20 * accuracy + 100;
mDatabaseHelper.updateRegionSignalStrength(cursor.getLong(0 /* _ID */), (int) accuracy);
}
} finally {
cursor.close();
}
mAdapter.swapCursor(mDatabaseHelper.getAllRegions());
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
#Override
public void onEnterRegion(final BeaconRegion region) {
try {
final Cursor cursor = mDatabaseHelper.findRegion(region);
try {
if (cursor.moveToNext()) {
final int event = cursor.getInt(6 /* EVENT */);
if (event == BeaconContract.EVENT_IN_RANGE) {
fireEvent(cursor);
}
}
} finally {
cursor.close();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
#Override
public void onExitRegion(final BeaconRegion region) {
try {
final Cursor cursor = mDatabaseHelper.findRegion(region);
try {
if (cursor.moveToNext()) {
final int event = cursor.getInt(6 /* EVENT */);
if (event == BeaconContract.EVENT_OUT_OF_RANGE) {
fireEvent(cursor);
}
}
} finally {
cursor.close();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
private void fireEvent(final Cursor cursor) {
try {
final boolean enabled = cursor.getInt(9 /* ENABLED */) == 1;
if (!enabled)
return;
final int action = cursor.getInt(7 /* ACTION */);
final String actionParam = cursor.getString(8 /* ACTION PARAM */);
switch (action) {
case BeaconContract.ACTION_MONA_LISA: {
stopScanning();
// final DialogFragment dialog = new MonalisaFragment();
// dialog.show(mParentFragment.getChildFragmentManager(), "JIRNG");
break;
}
case BeaconContract.ACTION_SILENT: {
stopScanning();
// final DialogFragment dialog = new tarh();
// dialog.show(mParentFragment.getChildFragmentManager(), "JIRING");
break;
}
case BeaconContract.ACTION_ALARM: {
stopScanning();
// final DialogFragment dialog = new rest();
// dialog.show(mParentFragment.getChildFragmentManager(), "Jiring");
break;
}
case BeaconContract.ACTION_URL: {
stopScanning();
try {
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(actionParam));
startActivity(intent);
} catch (final ActivityNotFoundException e) {
Toast.makeText(this, R.string.no_application, Toast.LENGTH_SHORT).show();
}
break;
}
case BeaconContract.ACTION_APP: {
stopScanning();
try {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setPackage(actionParam);
startActivity(intent);
} catch (final ActivityNotFoundException e) {
Toast.makeText(this, R.string.no_given_application, Toast.LENGTH_SHORT).show();
}
break;
}
case BeaconContract.ACTION_TASKER:
// switch (TaskerIntent.testStatus(getActivity())) {
// case OK:
// final TaskerIntent i = new TaskerIntent(actionParam);
final BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent recIntent) {
// if (recIntent.getBooleanExtra(TaskerIntent.EXTRA_SUCCESS_FLAG, false))
Toast.makeText(drawermenu.this, R.string.tasker_success, Toast.LENGTH_SHORT).show();
drawermenu.this.unregisterReceiver(this);
}
};
// getActivity().registerReceiver(br, i.getCompletionFilter());
// Start the task
// getActivity().sendBroadcast(i);
break;
// case NotEnabled:
// Toast.makeText(getActivity(), R.string.tasker_disabled, Toast.LENGTH_SHORT).show();
// break;
// case AccessBlocked:
// Toast.makeText(getActivity(), R.string.tasker_external_access_denided, Toast.LENGTH_SHORT).show();
// break;
// case NotInstalled:
// Toast.makeText(getActivity(), R.string.tasker_not_installed, Toast.LENGTH_SHORT).show();
// break;
default:
Toast.makeText(this, R.string.tasker_error, Toast.LENGTH_SHORT).show();
break;
}
// break;
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void onEditRegion(final long id) {
// final Intent intent = new Intent(this, BeaconsDetailsActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
// intent.putExtra(BeaconsDetailsActivity.ID, id);
// startActivity(intent);
}
public void onScannerClosedWithResult(final Beacon beacon) {
try {
mServiceConnection.stopRangingBeaconsInRegion(mScannerFragment);
mScannerFragment.dismiss();
mScannerFragment = null;
// final Cursor cursor = mDatabaseHelper.findRegionByBeacon(beacon);
minor = beacon.getMinor();
Intent intenta = new Intent(drawermenu.this, FragmentA.class);
switch (minor) {
case 99:
// startActivity(intenta);
popUp();
break;
case 246:
// startActivity(intenta);
// Toast.makeText(MainActivity.this, "246", Toast.LENGTH_LONG).show();
popUp();
break;
case 63:
popUp();
break;
case 104:
popUp();
break;
}
}
catch (Exception ex)
{
Log.e("ERROR", ex.getMessage());
}
}
private void popUp()
{
new Handler().post(new Runnable() {
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(drawermenu.this,FragmentA.class);
// mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
drawermenu.this.startActivity(mainIntent);
// Splash.this.finish();
}
});
}
public void onScannerClosed() {
try {
mServiceConnection.stopRangingBeaconsInRegion(mScannerFragment);
mScannerFragment = null;
startScanning();
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public DatabaseHelper getDatabaseHelper() {
return mDatabaseHelper;
}
private boolean ensureBleExists() {
try {
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.no_ble, Toast.LENGTH_LONG).show();
return false;
}
return true;
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
return false;
}
}
private boolean isBleEnabled() {
try {
final BluetoothManager bm = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
final BluetoothAdapter ba = bm.getAdapter();
return ba != null && ba.isEnabled();
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
return false;
}
}
private void enableBle() {
try {
final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (id == R.id.nav_home) {
// Handle the camera action
fragment = new ProfileFragment();
} else if (id == R.id.nav_points) {
fragment = new PointFragment();
} else if (id == R.id.nav_coupons) {
fragment = new CouponFragment();
} else if (id == R.id.nav_about) {
fragment = new AboutFragment();
}
fragmentTransaction.replace(R.id.appbar, fragment,fragment.getClass().getSimpleName());
fragmentTransaction.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
and this is the code which error is referring to:
package com.example.niloofar.showroom;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import no.nordicsemi.android.beacon.Beacon;
import no.nordicsemi.android.beacon.BeaconRegion;
import no.nordicsemi.android.beacon.BeaconServiceConnection;
import no.nordicsemi.android.beacon.Proximity;
/**
* Created by niloofar on 11/9/2016.
*/
public class BeaconScannerFragment extends DialogFragment implements BeaconServiceConnection.BeaconsListener {
// public class BeaconScannerFragment extends DialogFragment implements BeaconServiceConnection.BeaconsListener {
private boolean mCompleted;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCompleted = false;
}
#Override
public void onBeaconsInRegion(final Beacon[] beacons, final BeaconRegion region) {
if (!mCompleted) {
for (final Beacon beacon : beacons)
if (Proximity.IMMEDIATE == beacon.getProximity()) {
mCompleted = true;
final BeaconsFragment parentFragment = (BeaconsFragment) getParentFragment();
parentFragment.onScannerClosedWithResult(beacon);
dismiss();
break;
}
}
}
#NonNull
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
return new AlertDialog.Builder(getContext())
.setView(R.layout.fragment_scan).create();
}
#Override
public void onCancel(final DialogInterface dialog) {
super.onCancel(dialog);
final BeaconsFragment targetFragment = (BeaconsFragment) getParentFragment();
targetFragment.onScannerClosed();
}}
does anyone know how my problem will be solved?
This is the place where your problem occurs:
final BeaconsFragment parentFragment = (BeaconsFragment) getParentFragment();
parentFragment.onScannerClosedWithResult(beacon);
You initialize parentFragment, but the NullPointerException is thrown when you try to call onScannerClosedWithResult. This means that parentFragment is null. To solve this, you have three options. The first option is to use try-catch where you handle the NullPointerException. The second option is to make sure that getParentFragment will never return null. The third option is to fail gracefully when null is returned:
final BeaconsFragment parentFragment = (BeaconsFragment) getParentFragment();
if (parentFragment == null) {
parentFragment.onScannerClosedWithResult(beacon);
}

Android - How To Detect Whether a Headset Has a Microphone

I want to check whether a headset has a microphone or not. Currently I'm using this broadcast receiver code, but I'm not sure whether it is correct or not.
public class HeadSetMicrophoneStateReceiver extends BroadcastReceiver {
private String pluggedState = null;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("microphone", -1);
switch (state) {
case 0:
//Headset does not have a Microphone
pluggedState = "0";
break;
case 1:
//Headset have a Microphone
pluggedState = "1";
break;
default:
pluggedState = "I have no idea what the headset state is";
}
EventBus.getDefault().post(new HeadSetMicrophoneEvent(pluggedState));
}
}
}
Please help me out.
This method returns whether the microphone is available.
If it is not available then an exception will be caught.
public static boolean getMicrophoneAvailable(Context context) {
MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile(new File(context.getCacheDir(), "MediaUtil#micAvailTestFile").getAbsolutePath());
boolean available = true;
try {
recorder.prepare();
}
catch (IOException exception) {
available = false;
}
recorder.release();
return available;
}
try Following code
ackage com.example.headsetplugtest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
public class MyActivity extends Activity {
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
Log.d("MyActivity ", "state: " + intent.getIntExtra("state", -1));
Log.d("MyActivity ", "microphone: " + intent.getIntExtra("microphone", -1));
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
getApplicationContext().registerReceiver(mReceiver, filter);
}
#Override
protected void onStop() {
super.onStop();
getApplicationContext().unregisterReceiver(mReceiver);
}
}

how to set different ids for different estimote beacons?

Suppose, Android app is detecting 3 beacons with in range with default UUID value. So, how can i set/change the name for each beacons in Anndroid (to identify each beacon)?
Appreciations for any suggestions... Thanks
Beacons are identified not only by UUID, but also by their major and minor values, and this whole set (UUID + Major + Minor) is how you can differentiate between them.
Moreover, these values are hierarchical in nature, which allows you to put some structure into your beacon deployment. Consider this example:
Whole Museum: UUID = B9407F30-F5F8-466E-AFF9-25556B57FE6D
North Wing: Major = 1
Exhibit A: Minor = 1
Exhibit B: Minor = 2
South Wing: Major = 2
This way, when your device comes in range of a beacon B9407F30-F5F8-466E-AFF9-25556B57FE6D:1:2, just by looking at it you'll know that it's at the North Wing, Exhibit B.
this is i got a solution to set different ids for different beacons. and also identifying differnet beacons and sending notifications to the user when app not in foreground.
I initially confused where to change Major and Minor values of beacons.
Simply, i installed Estimote Android app from Playstore
here,
1. Click on Beacons
2. Select one beacon and it displays one more detailed activity in that you can change Values (for me i changed Minor values for all beacon based on my requirement).
So, now Minor values for all beacons changed as per your requirement. After that find the below code
In this below code I am sending notification if App is in background or else i am dirctly updating statuses in Activity main class.
I changed Beacons values as 1,2,3,4.
public class BeaconMyService extends Service {
private static final String TAG = "BeaconMyService";
private final Handler handler = new Handler();
private BeaconManager beaconManager;
private NotificationManager notificationManager;
private static final Region ALL_ESTIMOTE_BEACONS_REGION = new Region("rid",
null, null, null);
private static final int NOTIFICATION_ID = 123;
private Messenger messageHandler;
Bundle extras;
private String notifyMsg ="";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
extras = intent.getExtras();
messageHandler = (Messenger) extras.get("MESSENGER");
} catch (Exception e) {
// TODO: handle exception
}
Log.e(TAG, "Called=============");
if (beaconManager.isBluetoothEnabled()) {
connectToService();
}
return Service.START_NOT_STICKY;
}
private void connectToService() {
beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
try {
beaconManager.startRanging(ALL_ESTIMOTE_BEACONS_REGION);
} catch (RemoteException e) {
Log.e("Myservice",
"Cannot start ranging, something terrible happened");
Log.e("", "Cannot start ranging", e);
}
}
});
}
#Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
beaconManager = new BeaconManager(this);
beaconManager.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region region,
final List<Beacon> beacons) {
// Note that beacons reported here are already sorted by
// estimated
// distance between device and beacon.
for (int index = 0; index < beacons.size(); index++) {
Beacon beacon = beacons.get(index);
if (beacon != null) {
if (beacons.size() > 0) {
if (Utils.computeAccuracy(beacons.get(0)) < 1.0) {
try {
switch (beacons.get(0).getMinor()) {
case 1:
if (isAppInForeground(getApplicationContext())) {
Message message = Message.obtain();
message.arg1 = beacons.get(0)
.getMinor();
try {
messageHandler.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
} else {
postNotification(beacons.get(0)
.getMinor()
+ ". Welcome to Media Lab");
}
break;
case 2:
if (isAppInForeground(getApplicationContext())) {
Message message = Message.obtain();
message.arg1 = beacons.get(0)
.getMinor();
try {
messageHandler.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
} else {
postNotification(beacons.get(0)
.getMinor()
+ ". Welcome to Gaming Zone");
}
break;
case 3:
if (isAppInForeground(getApplicationContext())) {
Message message = Message.obtain();
message.arg1 = beacons.get(0)
.getMinor();
try {
messageHandler.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
} else {
postNotification(beacons.get(0)
.getMinor()
+ ". Welcome to eLearing Education");
}
break;
case 4:
if (isAppInForeground(getApplicationContext())) {
Message message = Message.obtain();
message.arg1 = beacons.get(0)
.getMinor();
try {
messageHandler.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
} else {
postNotification(beacons.get(0)
.getMinor()
+ ". Welcome to Retail Department");
}
break;
default:
break;
}
} catch (Exception e) {
// TODO: handle exception
}
}else{
if (isAppInForeground(getApplicationContext())) {
Message message = Message.obtain();
message.arg1 = 10;
try {
messageHandler.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
// Utils.computeAccuracy(beacons.get(0))
}
}
}
}
}
});
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
// ---helper method to determine if the app is in
// the foreground---
public static boolean isAppInForeground(Context context) {
List<RunningTaskInfo> task = ((ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE)).getRunningTasks(1);
if (task.isEmpty()) {
return false;
}
Log.e(TAG + "isAppInForeground-----",
""
+ task.get(0).topActivity.getPackageName()
.equalsIgnoreCase(context.getPackageName()));
return task.get(0).topActivity.getPackageName().equalsIgnoreCase(
context.getPackageName());
}
private void postNotification(String msg) {
if(!notifyMsg.equalsIgnoreCase(msg)){
notifyMsg = msg;
Intent notifyIntent = new Intent(BeaconMyService.this,
MainActivity.class);
notifyIntent.putExtra("content", msg);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivities(
BeaconMyService.this, 0, new Intent[] { notifyIntent },
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(
BeaconMyService.this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Monitoring Region").setContentText(msg)
.setAutoCancel(true).setContentIntent(pendingIntent).build();
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notificationManager.notify(NOTIFICATION_ID, notification);
}
}
}
Coming to Activity for updating status is this
package com.hcl.beacons_notification_ex;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
static TextView tv_items;
public static Handler messageHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_items = (TextView)findViewById(R.id.tv_items);
messageHandler = new MessageHandler();
}
public static class MessageHandler extends Handler {
#Override
public void handleMessage(Message message) {
int state = message.arg1;
switch (state) {
case 1:
tv_items.setText("Welcome to Media Lab");
break;
case 2:
tv_items.setText("Welcome to Gaming Zone");
break;
case 3:
tv_items.setText("Welcome to eLearing Education");
break;
case 4:
tv_items.setText("Welcome to Retail Department");
break;
default:
tv_items.setText("Going far to Range");
break;
}
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Intent i = new Intent(getApplicationContext(), BeaconMyService.class);
if(isMyServiceRunning(BeaconMyService.class)){
}else{
i.putExtra("MESSENGER", new Messenger(messageHandler));
startService(i);
// startService(i);
}
try {
if (getIntent().getExtras() != null) {
tv_items.setText(""
+ getIntent().getExtras().getString("content"));
}
} catch (Exception e) {
// TODO: handle exception
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
#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;
}
}
First of all you need estimote sdk
Then you can create a beaconDetection service something like this
public class BeaconMyService extends Service
{
private static final String TAG = "BeaconMyService";
private final Handler handler = new Handler();
private BeaconManager beaconManager;
private static final Region ALL_ESTIMOTE_BEACONS_REGION = new Region("rid", null, null, null);
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (beaconManager.isBluetoothEnabled())
{
connectToService();
}
return Service.START_NOT_STICKY;
}
private void connectToService()
{
beaconManager.connect(new BeaconManager.ServiceReadyCallback()
{
#Override
public void onServiceReady()
{
try
{
beaconManager.startRanging(ALL_ESTIMOTE_BEACONS_REGION);
}
catch (RemoteException e)
{
Log.e("Myservice", "Cannot start ranging, something terrible happened");
Log.e("", "Cannot start ranging", e);
}
}
});
}
#Override
public void onCreate()
{
super.onCreate();
beaconManager = new BeaconManager(this);
beaconManager.setRangingListener(new BeaconManager.RangingListener()
{
#Override
public void onBeaconsDiscovered(Region region, final List<Beacon> beacons)
{
// Note that beacons reported here are already sorted by
// estimated
// distance between device and beacon.
for (int index = 0; index < beacons.size(); index++)
{
Beacon beacon = beacons.get(index);
if (beacon != null)
{
Log.v("Beacon MacAddress", beacon.getMacAddress() + "");
if (!Constants.BEACONSDETECTEDLIST.containsKey(beacon.getMacAddress()))
{//Constants.BEACONSDETECTEDLIST is your list of beacon mac addresses
//public static HashMap<String, Long> BEACONSDETECTEDLIST = new HashMap<String, Long>();
//to check if beacon is detected for the first time
if (Constants.BEACON1.equalsIgnoreCase(beacon.getMacAddress()))
{//Constants.BEACON1 is mac address of beacon 1 assigned in constants
Constants.BEACONSDETECTEDLIST.put(beacon.getMacAddress(), System.currentTimeMillis());
handler.postDelayed(beacon1Detection, 2000);
}
else if (Constants.BEACON2.equalsIgnoreCase(beacon.getMacAddress()))
{
Constants.BEACONSDETECTEDLIST.put(beacon.getMacAddress(), System.currentTimeMillis());
handler.postDelayed(beacon2Detection, 2000);
}
}
else
{/*Do Nothing*/
}
}
}
}
});
}
private Runnable beacon1Detection = new Runnable()
{
public void run()
{
beacon1Info();
}
};
private Runnable beacon2Detection = new Runnable()
{
public void run()
{
beacon2Info();
}
};
private void beacon1Info()
{
Intent intent = new Intent(Constants.BEACON1BROADCAST_ACTION);
sendBroadcast(intent);
}//in Constants
//public static final String BEACON1BROADCAST_ACTION = "beacon1Action";
private void beacon2Info()
{
Intent intent = new Intent(Constants.BEACON2BROADCAST_ACTION);
sendBroadcast(intent);
}// in Constants
//public static final String BEACON2BROADCAST_ACTION = "beacon2Action";
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
handler.removeCallbacks(beacon1Detection);
handler.removeCallbacks(beacon2Detection);
super.onDestroy();
}
}
And then finally you need a BeaconBroadcastReceiver to receive the broadcasts in the service and open respective Activity
public class BeaconBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Constants.BEACON1BROADCAST_ACTION)) {
Intent intent2 = new Intent(context, Beacon1Layout.class);
context.startActivity(intent2);
} else if (intent.getAction().equals(Constants.BEACON2BROADCAST_ACTION)) {
Intent intent2 = new Intent(context, Beacon2Layout.class);
context.startActivity(intent2);
}
}
}
Hope this will help you, Good luck :)

My application isn't working smoothly

I am trying to develop a application. It is a radio application. When i use a method to show meta data that time it is creating some problem.
1.Play Pause button are not working smoothly.
2.Taking more time to show layout.
here is the main activity code:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;
public class IRadioActivity extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp = null;
private ImageButton btnPlay;
String title;
String artist;
private static Context con;
Timer timer;
TextView StationName;
String Stationurl = "http://95.211.82.139:8048";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
IRadioActivity.con = this;
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
mp = new MediaPlayer();
mp.setOnCompletionListener(this); // Important
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// check for already playing
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
}
}
}
});
playSong();
getMeta();
}
public void playSong() {
// Play song
try {
mp.reset();
mp.setDataSource(Stationurl);
mp.prepare();
mp.start();
// Displaying Song title
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onDestroy() {
super.onDestroy();
mp.release();
}
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
// ----------------
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
// .....top bar button....//
public void getMeta() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
URL url;
// Message msg = handler.obtainMessage();
try {
// url = new URL("http://relay5.slayradio.org:8000");
url = new URL(Stationurl);
final IcyStreamMeta icy = new IcyStreamMeta(url);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Typeface book = Typeface.createFromAsset(
// getAssets(), "fonts/Neutra2Text-Book.otf");
final TextView songTitle = (TextView) findViewById(R.id.songName);
final TextView artistName = (TextView) findViewById(R.id.artistName);
try {
artistName.setText(icy.getArtist().toString()
.trim());
artistName.setText(icy.getArtist().toString()
.trim());
songTitle.setText(icy.getTitle().toString()
.trim());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 0, 500);
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
}
}
Facing those problems when i use getMeta(); method.
Main Class for this method is:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IcyStreamMeta<Message> {
protected URL streamUrl;
private Map<String, String> metadata;
private boolean isError;
public IcyStreamMeta(URL streamUrl) {
setStreamUrl(streamUrl);
isError = false;
}
/**
* Get artist using stream's title
*
* #return String
* #throws IOException
*/
public String getArtist() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String title = streamTitle.substring(0, streamTitle.indexOf("-"));
return title.trim();
}
/**
* Get title using stream's title
*
* #return String
* #throws IOException
*/
public String getTitle() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String artist = streamTitle.substring(streamTitle.indexOf("-")+1);
return artist.trim();
}
public Map<String, String> getMetadata() throws IOException {
if (metadata == null) {
refreshMeta();
}
return metadata;
}
public void refreshMeta() throws IOException {
retreiveMetadata();
}
private void retreiveMetadata() throws IOException {
URLConnection con = streamUrl.openConnection();
con.setRequestProperty("Icy-MetaData", "1");
con.setRequestProperty("Connection", "close");
con.setRequestProperty("Accept", null);
con.connect();
int metaDataOffset = 0;
Map<String, List<String>> headers = con.getHeaderFields();
InputStream stream = con.getInputStream();
if (headers.containsKey("icy-metaint")) {
// Headers are sent via HTTP
metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
} else {
// Headers are sent within a stream
StringBuilder strHeaders = new StringBuilder();
char c;
while ((c = (char)stream.read()) != -1) {
strHeaders.append(c);
if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
// end of headers
break;
}
}
// Match headers to get metadata offset within a stream
Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
Matcher m = p.matcher(strHeaders.toString());
if (m.find()) {
metaDataOffset = Integer.parseInt(m.group(2));
}
}
// In case no data was sent
if (metaDataOffset == 0) {
isError = true;
return;
}
// Read metadata
int b;
int count = 0;
int metaDataLength = 4080; // 4080 is the max length
boolean inData = false;
StringBuilder metaData = new StringBuilder();
// Stream position should be either at the beginning or right after headers
while ((b = stream.read()) != -1) {
count++;
// Length of the metadata
if (count == metaDataOffset + 1) {
metaDataLength = b * 16;
}
if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
inData = true;
} else {
inData = false;
}
if (inData) {
if (b != 0) {
metaData.append((char)b);
}
}
if (count > (metaDataOffset + metaDataLength)) {
break;
}
}
// Set the data
metadata = IcyStreamMeta.parseMetadata(metaData.toString());
// Close
stream.close();
}
public boolean isError() {
return isError;
}
public URL getStreamUrl() {
return streamUrl;
}
public void setStreamUrl(URL streamUrl) {
this.metadata = null;
this.streamUrl = streamUrl;
this.isError = false;
}
public static Map<String, String> parseMetadata(String metaString) {
Map<String, String> metadata = new HashMap();
String[] metaParts = metaString.split(";");
Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$");
Matcher m;
for (int i = 0; i < metaParts.length; i++) {
m = p.matcher(metaParts[i]);
if (m.find()) {
metadata.put((String)m.group(1), (String)m.group(2));
}
}
return metadata;
}
}
Use prepareAsync() and not prepare(). See the documentation here: http://developer.android.com/guide/topics/media/mediaplayer.html#preparingasync

Categories

Resources