I am trying to detect and connect two Android mobiles using Wifi P2P method and I have been successful in it. But, I want a different name to be shown on the other device when it discovers mine.
Since, I am using Samsung J7 Prime 2(Android 9), changing Device name or Bluetooth name changes the Wifi P2p name, but the code for that didn't work. I tried the same code on Android 6.0.1 i.e. API 23 and it worked fine.
swtWifi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeDevName("Tony Stark");
}
});
public void changeDevName(String devNewName) {
try {
Method method = manager.getClass().getMethod("setDeviceName", WifiP2pManager.Channel.class, String.class, WifiP2pManager.ActionListener.class);
method.invoke(manager, channel, devNewName, 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();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Related
I am developing a camerax app for the image analysis use case. I built it and ran on my phone and it worked perfectly. I also tried it on a few other phones and it worked on them too. We actually plan to use the app on our raspberry pi 3B which has lineageOS installed and has necessary cameras attached and we have also tried running other apps that use camera on it and it worked perfectly. But, when I ran our app on it, it started, showed the animation that it was supposed to show and nothing else happened, like the app didn't crash, we also noticed the camera turning on and off a few times, but that's it. From the logs, I could see the app never runs the code in the setAnalyzer() block. Here's the code for the relevant part.
model=new LocalModel.Builder()
.setAssetFilePath("model.tflite")
.build();
CustomImageLabelerOptions customImageLabelerOptions=new CustomImageLabelerOptions.Builder(model)
.setConfidenceThreshold(.98f)
.setMaxResultCount(1)
.build();
labeler= ImageLabeling.getClient(customImageLabelerOptions);
analysis=new ImageAnalysis.Builder().setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.setTargetResolution(new Size(1280, 720))
.build();
Log.i(TAG, "before the analysis starts");
analysis.setAnalyzer(ContextCompat.getMainExecutor(this), image -> {
Log.i(TAG, "Analysis started");
int rotationDegrees = image.getImageInfo().getRotationDegrees();
#SuppressLint("UnsafeOptInUsageError") Image mediaImage=image.getImage();
if(mediaImage!=null){
InputImage i=InputImage.fromMediaImage(mediaImage, rotationDegrees);
labeler.process(i).addOnSuccessListener(new OnSuccessListener<List<ImageLabel>>() {
#Override
public void onSuccess(#NonNull #NotNull List<ImageLabel> imageLabels) {
Log.i(TAG, "successfully started to process the image");
String labels="";
for(ImageLabel label: imageLabels){
Log.i(TAG, label.getText());
labels=label.getText();
Log.i(TAG, labels);
}
if(labels.equalsIgnoreCase("dew")) {
isDetectingBottles=true;
d.stop();
imageView.setBackgroundResource(R.drawable.unnffffamed);
}
else{
if(isDetectingBottles){
isDetectingBottles=false;
imageView.setBackgroundResource(R.drawable.blink_animation);
d= (AnimationDrawable) imageView.getBackground();
d.start();
}
}
image.close();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Log.i(TAG, "ImageLabeling process failed");
e.printStackTrace();
image.close();
}
});
}
});
CameraSelector selector= CameraSelector.DEFAULT_BACK_CAMERA;
Log.i(TAG, "before binding to lifecycle");
ListenableFuture<ProcessCameraProvider> m=ProcessCameraProvider.getInstance(this);
m.addListener(new Runnable() {
#Override
public void run() {
try {
m.get().bindToLifecycle((LifecycleOwner) MainActivity.this, selector, analysis);
}
catch(InterruptedException e){
e.printStackTrace();
}
catch(ExecutionException e){
e.printStackTrace();
}
}
}, ContextCompat.getMainExecutor(this));
Here are a few thing I tried:
At the beginning I didn't set any target resolution and left it to camerax but it still didn't work back then.
I tried using different cameras with the selector, using the front camera leads to a crash.
Tried calling image.close() at the end of setAnalyzer block, but that's obviously not the issue since it works on other devices.
NOTE: the logs don't show any exceptions as for me to get an idea of what's happening.
I have a Android Studio project with firebase, I already implement firebase correctly.
im trying to make a sign in with sms authentication, everything works but no sms arrives
I already configure firebase authentication
here's some code
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
Toast.makeText(MainActivity.this, "Verification Complete", Toast.LENGTH_SHORT).show();
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(MainActivity.this, "Verification Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
Toast.makeText(MainActivity.this, "Code Sent", Toast.LENGTH_SHORT).show();
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bt_send_otp:
PhoneAuthProvider.getInstance().verifyPhoneNumber(
etPhone.getText().toString(), // Phone number to verify
1, // Timeout duration
TimeUnit.MINUTES, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
break;
case R.id.bt_resend_otp:
break;
case R.id.bt_verify_otp:
break;
}
}
when I press the send otp button the toast "Code Sent" appears
Thanks for the help :)
Since it is a test number, OTP will not arrive. Though for testing you can use the verification code you added with the test phone number on the console.
Firebase Console Dashboard -> Authentication -> SignIn Method -> Phone -> Phone numbers for testing.
Check out the docs for Firebase Phone Verification for Android : https://firebase.google.com/docs/auth/android/phone-auth?authuser=1#test-with-whitelisted-phone-numbers
all.
I try to create an android cast application with google chromecast. So I tryied to find chromecast with this code:
public void startDiscoveringDevices() {
DiscoveryManager.init(mContext);
mDiscoveryManager = DiscoveryManager.getInstance();
mDiscoveryManager.registerDeviceService(CastService.class, CastDiscoveryProvider.class);
mDiscoveryManager.setPairingLevel(DiscoveryManager.PairingLevel.ON);
mDiscoveryManager.setCapabilityFilters(new CapabilityFilter(
MediaPlayer.Any,
MediaControl.Any,
VolumeControl.Any
));
mDiscoveryManager.addListener(this);
mDiscoveryManager.start();
Log.wtf("CastDeviceManager", "discovery manager was started");
}
After this I listen DiscoveryManagerListener:
// ********************* My DiscoveryManagerListener ********************************** //
#Override
public void onDeviceAdded(DiscoveryManager manager, ConnectableDevice device) {
Log.wtf("DiscoveryManagerListener", "Device added");
device.addListener(...); // Here I pass implementation of ConnectableDeviceListener interface.
device.connect(); // connect to device
}
#Override
public void onDeviceUpdated(DiscoveryManager manager, ConnectableDevice device) {
Log.wtf("DiscoveryManagerListener", "Device updated");
device.addListener(...); // Here I pass implementation of ConnectableDeviceListener interface.
// try to connect to device, if it not connected yet
if (device.isConnected()) {
device.disconnect();
}
else {
device.connect();
}
}
#Override
public void onDeviceRemoved(DiscoveryManager manager, ConnectableDevice device) {
Log.wtf("DiscoveryManagerListener", "Device removed");
mCastDevices.remove(device.hashCode()); // remove device from list of devices
}
#Override
public void onDiscoveryFailed(DiscoveryManager manager, ServiceCommandError error) {
Log.wtf("DiscoveryManagerListener", "Device(s) not found", error);
destroyDiscoveryManager();
}
// ************************************************************************************ //
// ************************** My ConnectableDeviceListener **************************** //
#Override
public void onDeviceReady(ConnectableDevice device) {
Log.wtf("ConnectableDeviceListener", "device ready");
outDeviceInfo(device, "ConnectableDeviceListener");
// put to map with devices new connected device
mCastDevices.put(device.hashCode(), new CastDevice(device, mCastLifecycleListener));
Log.wtf("ConnectableDeviceListener", "Count cast devices: " + mCastDevices.size());
}
#Override
public void onDeviceDisconnected(ConnectableDevice device) {
Log.wtf("ConnectableDeviceListener", "device disconnected");
destroyDiscoveryManager();
}
#Override
public void onPairingRequired(ConnectableDevice device, DeviceService service, PairingType pairingType) {
Log.wtf("ConnectableDeviceListener", "device paring required");
}
#Override
public void onCapabilityUpdated(ConnectableDevice device, List<String> added, List<String> removed) {
Log.wtf("ConnectableDeviceListener", "capability updated");
}
#Override
public void onConnectionFailed(ConnectableDevice device, ServiceCommandError error) {
Log.wtf("ConnectableDeviceListener", "connection failed");
destroyDiscoveryManager();
}
// ************************************************************************************ //
// this method I use to disconnect from devices in map and stop discovering new devices
public void destroyDiscoveryManager() {
mDiscoveryManager.stop();
DiscoveryManager.destroy();
Log.wtf("CastDeviceManager", "discovery manager was stopped");
for (Map.Entry<Integer, CastDevice> castDeviceEntry: mCastDevices.entrySet()) {
castDeviceEntry.getValue().stopCast();
castDeviceEntry.getValue().disconnect();
Log.wtf("CastDevice", "device.isConnected(): " + castDeviceEntry.getValue().isConnected());
}
mCastDevices.clear();
}
In my Activity I call startDiscoveringDevices() and destroyDiscoveryManager() by buttons. And all was fine, but in one time it stop finding devices. I wasn't change anything in code.
Maybe I made something with bugs and it worked, but now something happened and it doesn't work now? What I doing wrong?
I am developing an Android app that is going to communicate with target miroprocessor(ARM processor) board through a bluetooth device(RN4020).
Since the pair PIN is random for each bluetooth module, I just want the app source code to connect the app with that RN4020 module (without pairing manually since I don't know the pair PIN).
Also, I just want to know the UUID for RN4020 module, I have tried to find the UUID through some Android app it shows more than ten UUIDs. I am confused to choose the appropriate UUID.
Here is my code:
private static String address = "00:1E:C0:19:DB:A6";
private static final UUID MY_UUID = UUID.fromString("00002A00-0000-1000-8000-00805F9B34FB");
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View V)
{
Toast.makeText(getApplicationContext(), "Connecting to ... RN4020_D694", Toast.LENGTH_SHORT).show();
if (mBluetoothAdapter.isEnabled())
Connect();
}
});
public void Connect() {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Toast.makeText(getApplicationContext(), "Connecting to ... " + device, Toast.LENGTH_SHORT).show();
mBluetoothAdapter.cancelDiscovery();
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
Toast.makeText(getApplicationContext(), "Connection made", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
changingText.setText("Unable to end the connection");
}
Log.d(TAG, "Socket creation failed");
}
beginListenForData();
}
When I tried to press the connect button, my app got stuck and it's not responding.
To avoid pairing you need to go for an insecure UUID rfcomm.
Replace:
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
with
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
I have a CC2540 BLE kit and i want to see the battery level of the kit in my smartphone app. I have made the code, which gets the battery level from the kit. The battery level is called BodySensor in this case:
First, i will go into the characteristic value of the battery service part for the kit. So i use the Service and Characteristic UUID's for the battery service:
public void getBodySensorLoc(BluetoothDevice device)
{
Log.i(TAG, "getBodySensorLoc");
BluetoothGattService mHRP = mBluetoothGatt.getService(device, HRP_SERVICE);
if (mHRP == null)
{
Log.e(TAG, "getBodySensorLoc: mHRP = null");
return;
}
BluetoothGattCharacteristic mBSLcharac = mHRP.getCharacteristic(BODY_SENSOR_LOCATION);
if (mBSLcharac == null) {
Log.e(TAG, "getBodySensorLoc: mBSLcharac = null");
return;
}
mBluetoothGatt.readCharacteristic(mBSLcharac);
}
My purpose is to read the battery level, when pressing a button in my application. So i implement this button in my Activity class:
((Button) findViewById(R.id.btn_BSL)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
mService.getBodySensorLoc(mDevice);
}
});
This kit will automatically send the battery level back to the smartphone. So i will set focus on onCharacteristicRead method of BluetoothGattCallback part in my code:
private BluetoothGattCallback mGattCallbacks = new BluetoothGattCallback()
{
public void onCharacteristicRead(BluetoothGattCharacteristic charac, int status)
{
UUID charUuid = charac.getUuid();
Bundle mBundle = new Bundle();
Message msg = Message.obtain(mActivityHandler, HRP_VALUE_MSG);
Log.i(TAG, "onCharacteristicRead");
if (charUuid.equals(BODY_SENSOR_LOCATION))
mBundle.putByteArray(BSL_VALUE, charac.getValue());
msg.setData(mBundle);
msg.sendToTarget();
}
};
I want the application to show the received battery level in a textview. The kit sends the battery level as a integer, so if the level is 70%, it sends "70". The code includes a Handler in the Activity class:
private Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case HRPService.HRP_VALUE_MSG:
Log.d(TAG, "mHandler.HRP_VALUE_MSG");
Bundle data1 = msg.getData();
final byte[] bslval = data1.getByteArray(HRPService.BSL_VALUE);
runOnUiThread(new Runnable()
{
public void run()
{
if (bslval != null)
{
try {
Log.i(TAG, "BYTE BSL VAL =" + bslval[0]);
TextView bsltv = (TextView) findViewById(R.id.BodySensorLocation);
bsltv.setText("\t" + mContext.getString(R.string.BodySensorLocation)
+ getBodySensorLocation(bslval[0]));
} catch (Exception e)
{
Log.e(TAG, e.toString());
}
}
}
});
default:
super.handleMessage(msg);
}
}
};
The problem is that the textview doesn't show anything, when i press this button in my application after i connected my smartphone with the kit. Can anyone tell me, where the problem is ?.
Thanks in advance
Unsure what exact kit you have. Unsure if they all have battery level measuring hardware on board. Maybe this is the reason.