Android: Monitoring Bluetooth Discovery - what does this compile error mean? - android

I'm learning Bluetooth programming on Android using the Wrox Professional Android 2 Application Development book. The discovery monitor example (pg 432) has this code snippet:
BroadcastReceiver discoveryMonitor = new BroadcastReceiver() {
String dStarted = BluetoothAdapter.ACTION_DISCOVERY_STARTED;
String dFinished = BluetoothAdapter.ACTION_DISCOVERY_FINISHED;
#Override
public void onReceive(Context context, Intent intent) {
if (dStarted.equals(intent.getAction())) {
// Discovery has started.
Toast.makeText(getApplicationContext(),
"Discovery Started...", Toast.LENGTH_SHORT).show();
}
else if (dFinished.equals(intent.getAction())) {
// Discovery has completed.
Toast.makeText(getApplicationContext(),
"Discovery Completed...", Toast.LENGTH_SHORT).show();
}
}
};
registerReceiver(discoveryMonitor,
new IntentFilter(dStarted));
registerReceiver(discoveryMonitor,
new IntentFilter(dFinished));
... and on each of the two registerReceiver calls at the end I get . . .
Syntax error on tokens, AnnotationName expected instead
Syntax error, insert "Type VariableDeclaratorId" to complete FormalParameterList
What's an annotationName and what's going wrong here?
Thanks in advance!!

Your problem is that you defined variables dStarted and dFinished as locals for discoveryMonitor BroadcastReceiver,
That way, you can't use them in registerReceiver(...)
You have to define them as global, or use
registerReceiver(discoveryMonitor, new
IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
instead.

Related

How to WifiP2pDevice.deviceName for current device?

I know similar questions are asked but the answers didn't work for me. I tried this answer but it throws null pointer exception. I also saw this answer but WifiP2pManager does not have any property or method that returns device name.
Can anyone please help?
I basically want to show user their device name and let them change it if they want to set custom name.
Thanks.
If you're still looking for the answer, here's how:
Identify own device name
This becomes available upon receiving the WIFI_P2P_THIS_DEVICE_CHANGED_ACTION intent in your broadcast receiver. Simply use the deviceName member variable like so:
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
WifiP2pDevice self = (WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
// Now self.deviceName gives you own device name
} else if(WifiP2pManager.WIFI_P2P...) {
...
2. Change own device name
There's no method to change the device name using the WifiP2pManager as per the develper docs, and although a public setDeviceName() method exists in the source code, you can't call it on your object (probably to keep devs from calling it on an object representing a nearby peer device). What worked for me was to obtain a Method object representing said method and invoking it on my WifiP2pManager instance:
private WifiP2pManager manager;
private WifiP2pManager.Channel channel;
...
public void changeDeviceName(String deviceNewName) {
try {
Method method = manager.getClass().getMethod("setDeviceName", WifiP2pManager.Channel.class, String.class, WifiP2pManager.ActionListener.class);
method.invoke(manager, channel, deviceNewName, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Name successfully changed", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Request failed: " + reason, Toast.LENGTH_SHORT).show();
Log.d(TAG, "Name change failed: " + reason);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Alternatively, users can rename their device manually from the advanced WiFi settings (Preferences > Advanced > WiFi Direct > Configure Device),
EDIT: Starting with Pie, use of non-SDK interfaces (essentially classes, variables or methods marked with #hide, which you access using reflection) is being restricted and will eventually be disallowed. The above method is currently greylisted (which means support for reflecting it might be removed in the future). Read up more here: https://developer.android.com/distribute/best-practices/develop/restrictions-non-sdk-interfaces

Incomings Call with Android Sip stack in Embarcadero C++ builder

I'm trying to receive calls on my SIP application at Embarcadero with C++ builder
and I'm not able to get it. My situation is as follows:
I've made an Asterisk server, I've created several accounts to be able to do the
tests and I've downloaded the Zoiper application for both Windows and Android.
In my designed application, I'm able to make calls to those accounts registered
in Zoiper, although not through events, it seems that the listener does not
listen, and I've done it through the status changes in the call.
The Java code is like this:
SipAudioCall.Listener listener = new SipAudioCall.Listener() {
#Override
public void onCallEstablished(SipAudioCall call) {
call.startAudio();
call.setSpeakerMode(true);
call.toggleMute();
Log.d("on call established", "on call established");
}
#Override
public void onCallEnded(SipAudioCall call) {
finish();
}
};
In Embarcadero C++ builder I think it would be like this (it doesn't work)
Compiles and executes but the event never occurs:
//The Manifest counts as the necessary permissions for Android, Internet and Sip.
_di_JSipAudioCall_Listener audioCall_Listener;
_di_JSipSession_Listener sessionListener;
_di_JSipSession session;
_di_JSipManager;
_di_JSipAudioCall audioCall;
_di_JSipProfile profile;
_di_JString uri;
_di_JString uri_llamada;
void onCallEstablished2(SipAudioCall call);
//The process of profile creation and instantiation of SipManager are programmed
//and compiled and do not give any problem.
audioCall_listener = TJSipAudioCall_Listener::JavaClass->init();
audioCall_listener->onCallEstablished = onCallEstablished2;
sessionListener = TJSipSession_Listener::JavaClass->init();
session = manager->createSipSession(profile,sessionListener);
audioCall = manager->makeAudioCall(uri,uri_llamada,audioCall_listener,15);
void onCallEstablished2(SipAudioCall call)
{
audioCall->startAudio();
audioCall->setSpeakerMode(true);
}
The code made in Embarcadero C++ builder that works:
//The Manifest counts as the necessary permissions for Android, Internet and Sip.
_di_JSipAudioCall_Listener audioCall_Listener;
_di_JSipSession_Listener sessionListener;
_di_JSipSession session;
_di_JSipManager;
_di_JSipAudioCall audioCall;
_di_JSipProfile profile;
_di_JString uri;
_di_JString uri_llamada;
//The process of profile creation and instantiation of SipManager are programmed
//and compiled and do not give any problem.
audioCall_listener = TJSipAudioCall_Listener::JavaClass->init();
audioCall_listener->onCallEstablished = onCallEstablished2;
sessionListener = TJSipSession_Listener::JavaClass->init();
session = manager->createSipSession(profile,sessionListener);
audioCall = manager->makeAudioCall(uri,uri_llamada,audioCall_listener,15);
Timer1->Enabled = true;
void __fastcall TMainForm::Timer1Timer(TObject *Sender)
{
if (audioCall->getState() == 8)
{
audioCall->startAudio();
audioCall->setSpeakerMode(true);
}
if(audioCall->getState() == 0)
{
audioCall->endCall();
}
}
As for the Java code for receiving calls, I have found examples here
No ringing event on incoming calls
and here
Android Sip incoming Call using Service with Broadcast Receiver,
but they are all event based, which doesn't seem to work for me.
I have also tried to do the IncomingReceiver class, which extends from
BroadcastReceiver and at the Embarcadero gives me problems.
Class made in Embarcadero with C++ builder (not compiles):
class IncomingReceiver: public JBroadcastReceiver{
public:
__fastcall IncomingReceiver();
_di_JSipAudioCall incomingCall;
void onReceive(_di_JContext contexto, _di_JIntent intento);
void accept();
void showIncomingCallGui(_di_JIntent intento, _di_JContext contexto);
};
So, my questions are:
Why don't events work for me?
Can I receive calls without events?
If so, what would it be like without events?
What do I do if I can't get the IncomingReceiver class?
I found a page (in spanish): http://lfgonzalez.visiblogs.com/cbuilder-10-2-tokyo-jni-broadcastreceiver-android/ in which it is explained the use of BroadcastReceiver in Embarcadero C++ Builder. Maybe with this information you can get the events working in order to receive calls.

cognalys verification error 550 and 551

I'm using cognalys sdk in my app for user verification but i get the errors 551 and 550 which are not listed on their site and I don't know what are they, here is the code I use:
Cognalys.verifyMobileNumber(SignupActivity.this,"token",
"id","number",
new VerificationListner() {
#Override
public void onVerificationStarted() {
Toast.makeText(getApplicationContext(), "Started", Toast.LENGTH_LONG).show();
}
#Override
public void onVerificationFailed(ArrayList<String> errorList) {
for (String error : errorList) {
Log.d("abx", "error:"+error);
}
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
#Override
public void onVerificationSuccess() {
Toast.makeText(getApplicationContext(), "Signed up successfully !", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignupActivity.this, SetPictures.class);
startActivity(intent);
finish();
}
});
instead of number I put my number from my code, I get the missed call but the toast "failed" shows up with error 550 in my log, can anybody tell me what does it mean?
Error codes: https://www.cognalys.com/androidlibraryerrors/
Android lib source code: https://github.com/cognalys/cognalys-android-library
Don't use the jar from their website. Download the one on github and include it in your project. Then you have to make a change in their code.
In the class CallListnerHelper, when a call comes, the incoming number is compared to a list of numbers they send. On my Xperia Z3c, the incoming number starts with 00. They send the list of excepted number all starting with '+'. The comparison always fails, so you have to handle that. Use the following library: https://github.com/googlei18n/libphonenumber
We are now Sending number numbers list/array With + and 00 . Can you guys please re-check .We should know the problem is fixed or not . Thanks for the valuable update

Using Android IBeacon Library on Service

I´m using the Android IBeacon Library for a Project. I need to create a Service that starts ranging for beacons in the background and notify the user when it finds one (the nearest one). I have searched a lot and coded based on many examples I have found, but still it doesn´t work. Using logs I found that the IBeaconManager doesn't bind, so onIBeaconServiceConnect never gets called. I have already tried some solutions I found here but none of them has been useful. I would really appreciate if someone could help me solving this problem. I post some of my code here
public class RangingService extends Service implements IBeaconConsumer
{
private IBeaconManager beaconManager;
#Override
public void onCreate()
{
super.onCreate();
beaconManager = IBeaconManager.getInstanceForApplication(this);
Log.d("RangingService","Created beaconManager instance");
beaconManager.setBackgroundBetweenScanPeriod(120000);
beaconManager.setBackgroundScanPeriod(30000);
beaconManager.bind(this);
if(beaconManager.isBound(this))
{
Log.d("RangingService","Beacon manager bound");
}
else
{
Log.d("RangingService","Beacon manager not bound");
}
//Show the service has started
notify("RangingService created", "RangingService has started");
}
#Override
public void onDestroy()
{
super.onDestroy();
beaconManager.unBind(this);
}
#Override
public void onIBeaconServiceConnect()
{
Log.d("RangingService", "Entering onIBeaconServiceConnect");
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<IBeacon> beacons, Region region)
{
if(beacons.size() > 0)
{
IBeacon nearestBeacon = beacons.iterator().next();
for(IBeacon b : beacons)
{
if(nearestBeacon.getProximity() == IBeacon.PROXIMITY_UNKNOWN)
{
nearestBeacon = b;
}
else
{
if(b.getProximity() != IBeacon.PROXIMITY_UNKNOWN)
{
if(b.getAccuracy() < nearestBeacon.getAccuracy())
{
nearestBeacon = b;
}
}
}
}
Log.d("RangingService","Nearest Beacon Found "+nearestBeacon.getMajor()+";"+nearestBeacon.getMinor());
notify("Beacon read","Major: "+nearestBeacon.getMajor()+"; Minor: "+nearestBeacon.getMinor());
}
else
{
Log.d("RangingService","No beacons");
}
}
});
try
{
Log.d("RangingService", "Entering startRangingBeacons");
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
}
catch(RemoteException e)
{
notificar("Error", e.getMessage());
Log.e("RangingService", "Error while starting scanning: "+e.getMessage());
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.d("RangingService", "Entering onBind");
return null;
}
The Service is already in my manifest also. Thanks for your help.
A couple of points:
The code indicates you are using a 0.x version of the Android iBeacon Library. If you are starting a new project, I would strongly recommend you use the Android Beacon Library 2.0, as the earlier library is no longer actively maintained, and it is now hard to find documentation for it.
Regardless of the library version you are using, you should be able to get a callback to the onBeaconServiceConnect() method after you bind to the BeaconManager. The fact that you don't get this callback probably indicates that the BeaconService is not starting up properly.
The most likely reason that the BeaconService is not starting up properly is because it is not properly declared in the manifest. If you are using Eclipse, you must edit your project.properties file and add the line: manifestmerger.enabled=true. If you are using AndroidStudio, this is not necessary. If you are using IntelliJ, you may have to declare the service manually.
You can verify if the manifest has the proper entries by looking at the generated manifest file in bin/AndroidManifest.xml, and verifying it has an entry for the BeaconService.
I had faced similar issues. Got resolved by doing following things
In eclipse project.properties added manifestmerger.enabled=true
restarted the eclipse
uninstalled other beacon apps in my android phone and restarted the phone

Android SpeechRecognizer when do I get ERROR_CLIENT when starting the voice recognizer?

I am not sure about some documentation related stuff.
To sum up what I did and what I want to to: I managed to introduce voice recognition feature into an Android application that is running on Android 4.2 on a tablet, and it works ok. Now I want to port my application on Google Glass but unfortunately I get the following error when I try to start the speech recognizer: error 5 -> ERROR_CLIENT(Other client side errors). The message guides me to find other errors that not related to SpeechRecognizer object, but I don't get any in my logs, not even warnings. So my question would be: When exactly do I get ERROR_CLIENT? and what should look the errors that block the recognizer to start?
Thank you! :)
I found this link that is the source code for producing the errors.
SpeechRecognizer source
There are 7 places where a search found "ERROR_CLIENT"
Here's the log statements right before the ERROR_CLIENT is sent to onError
Log.e(TAG, "no selected voice recognition service");
Log.e(TAG, "bind to recognition service failed");
Log.e(TAG, "startListening() failed", e);
Log.e(TAG, "stopListening() failed", e);
Log.e(TAG, "cancel() failed", e);
Log.e(TAG, "not connected to the recognition service");
Of course you can find more info at the above link, but this should give you the general reasons why you'd get ERROR_CLIENT
So after a bit of pain I manage to solve my problem regarding my glass application.
First of all I found that SpeechRecognizer only works when my glasses are connected to the internet! Even so I still received from times to times ERROR 5. That was because I have a bad connectivity to the internet and from times to times my glass just disconnected from the internet without any notifications! I think this is an issue that must be solved for the next level of glasses. It just cannot disconnect from the internet without notifying you.
So one of the causes for ERROR_CLIENT(5) on Google Glass is: not having internet connection
I got this error because I was using an object variable inside the main loop:
class SpeechRecognition implements RecognitionListener {
private SpeechRecognizer recognizer;
public void transcribe (Activity activity) {
new Handler(Looper.getMainLooper()).post(() -> {
this.speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this.activity);
this.speechRecognizer.setRecognitionListener(this.listener);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
this.speechRecognizer.startListening(intent);
}
}
[...]
}
Solution:
class SpeechRecognitionRunnable implements Runnable {
private volatile SpeechRecognizer speechRecognizer;
private RecognitionListener listener;
private Activity activity;
public SpeechRecognitionRunnable (RecognitionListener listener, Activity activity) {
this.listener = listener;
this.activity = activity;
}
#Override
public void run() {
this.speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this.activity);
this.speechRecognizer.setRecognitionListener(this.listener);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
this.speechRecognizer.startListening(intent);
}
public SpeechRecognizer getSpeechRecognizer() {
return this.speechRecognizer;
}
}
class SpeechRecognition implements RecognitionListener {
private SpeechRecognizer recognizer;
public void transcribe (Activity activity) {
new Handler(Looper.getMainLooper()).post(new SpeechRecognitionRunnable(this, activity)
}
[...]
}
The error happens also if the Google search application has no permissions to the microphone. In that case, the phone speech recognition service will be disabled and the ERROR_CLIENT error will be triggered for all apps (the above case was verified on a Samsung phone running Android 11)

Categories

Resources