Related
I try to implement Connection between two devices(Any ios/Android) and transfer text using BLE
I try too many demos from GitHub and also try from documentation step by step but I am not getting a success
some time give Error like :
> GATT server 133
or
>android.bluetooth.BluetoothGattCharacteristic android.bluetooth.BluetoothGattService.getCharacteristic(java.util.UUID)' on a null object reference
Please help me
Thank you so much
Here is the my two activity code one ble class and one activity to call function from BLE claass
I want just pass small text to android to android or android to ios using ble
please help I tried from too many days
================================================================
public class MainActivity extends AppCompatActivity {
ArrayList<String> getDevicess;
List<BluetoothDevice> getConnectedDevicess;
TextView tvscan;
TextView tvConnected;
TextView tvsend;
Ble ble;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvsend = (TextView) findViewById(R.id.tvsend);
getDevicess = new ArrayList<>();
getConnectedDevicess = new ArrayList<>();
ble = new Ble(this, getApplicationContext(), "zad");
ble.enableBle();
ble.checkPermission(0);
ble.scanLeDevice(true, 1000);
//after scan and connect click on send button then give error
tvsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ble.writeCharacteristics(hexStringToByteArray("abcdefg"), UUID.fromString("fffffff0-00f7-4000-b000-000000000000"), UUID.fromString("fffffff5-00f7-4000-b000-000000000000"));
}
});
}
public byte[] hexStringToByteArray(String s) {
int len = s.length()-1;
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}
return data;
}
}
===========================================BLE CLass==================
// Function To Write Characteristics .. !
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public void writeCharacteristics(byte[] data, UUID DLE_SERVICE, UUID DLE_WRITE_CHAR) {
BluetoothGattService Service = mBluetoothGatt.getService(DLE_SERVICE);
if (Service == null) {
Log.d(TAG, "service not found!");
//return false;
}
BluetoothGattCharacteristic charc1 = Service.getCharacteristic(DLE_WRITE_CHAR);
if (charc1 == null) {
Log.d(TAG, "char not found!");
Log.d(TAG, "CHARAC_-TRST" + charc1.getUuid());
// return false;
}
// charc1.setValue(new byte[]{0x00, 0x05, 0x10, 0x01, 0x3E, 0x01, 0x23});
charc1.setValue(data);
boolean stat = mBluetoothGatt.writeCharacteristic(charc1);
Log.d(TAG, "FINISHED WRITTING CHAR 1 status write :(status)" + stat);
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
}
}
This snippet is problematic:
public void displayBleService(List<BluetoothGattService> gattServices) {
Log.d(TAG, "display Services");
List<BluetoothGattCharacteristic> characteristics = new ArrayList<BluetoothGattCharacteristic>();
for (BluetoothGattService services : gattServices) {
Log.d(TAG, "SERVICES == ." + services.getUuid());
characteristics = services.getCharacteristics();
for (BluetoothGattCharacteristic characteristic : characteristics) {
Log.d(TAG, "CAHRACTERISTICS == ." + characteristic.getUuid() + "--" + characteristic.getProperties());
//enableNotification(characteristic, true);
}
}
}
the services is null, and thus the services.getCharacteristics() is provoking the NPE.
Please debug your code, and make sure you have BLUETOOTH_ADMIN permission as well. Feel free to add necessary null-guards as well at your own discretion.
I am using BluetoothAdapter.LeScanCallback to scan for BLE devices. Once I get the required scanned data, I would like to display it on a textview. However, the textview is not updated with the scanned data. Appreciate if anyone could help on this.
private TextView TV_uuid;
private TextView TV_major;
private TextView TV_minor;
//Find BLE devices
private Runnable scanRunnable = new Runnable() {
#Override
public void run() {
if (isScanning) {
if (btAdapter != null) {
btAdapter.stopLeScan(leScanCallback);
}
} else {
if (btAdapter != null) {
btAdapter.startLeScan(leScanCallback);
}
}
isScanning = !isScanning;
scanHandler.postDelayed(this, scan_interval_ms);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TV_uuid = (TextView)findViewById(R.id.tv_uuid2);
TV_major = (TextView)findViewById(R.id.tv_major2);
TV_minor = (TextView)findViewById(R.id.tv_minor2);
//start scan BLE
scanHandler.post(scanRunnable);
}
private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice bluetoothDevice, final int rssi, final byte[] scanData) {
if (scanData[7] == 0x02 && scanData[8] == 0x15) { // iBeacon indicator
UUID uuid = getGuidFromByteArray(Arrays.copyOfRange(scanData, 9, 25));
int major = (scanData[25] & 0xff) * 0x100 + (scanData[26] & 0xff);
int minor = (scanData[27] & 0xff) * 0x100 + (scanData[28] & 0xff);
byte txpw = scanData[29];
Log.i(TAG, "iBeacon Major = " + major + " | Minor = " + minor + " TxPw " + (int)txpw + " | UUID = " + uuid.toString());
TV_uuid.setText(uuid.toString());
TV_major.setText(major);
TV_minor.setText(minor);
}
}
};
If I remember correctly, that callback runs on a separate thread, so you shouldn't put view updates in the callback directly. If you just want to test, you can wrap the view updates inside a runOnUiThread() call and see if that works.
runOnUiThread(new Runnable(){
public void run(){
//set the value of your textviews here
}
}
}
Ideally though you should be decouple the scanning from the Activity. I'd put BLE scanning code inside a service that is either bound by a client Activity, or sends update to listening clients using LiveData / local broadcast manager.
Probably if (scanData[7] == 0x02 && scanData[8] == 0x15) is preventing the code to execute. Or you forgot to start the scan and install the onLeScanCallback listener
I've created an Android app to communicate with my Arduino using Bluetooth. But when I'm sending data from my Android device to my Arduino, the Arduino isn't responding to what I've send. I am able to get a connection from my Android device to my Arduino. So that's not the problem.
Here's my full script for Android.
package nl.handoko.LumaMini;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "LumaMini";
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
Button fourty, thirty, twenty, twelve, automatic, manual;
TextView message;
// Well known SPP UUID
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Server's MAC address
private static String address = "98:D3:31:30:09:43";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "In onCreate()");
setContentView(R.layout.activity_mainnn);
fourty = (Button) findViewById(R.id.button1);
thirty = (Button) findViewById(R.id.button4);
twenty = (Button) findViewById(R.id.button2);
twelve = (Button) findViewById(R.id.button5);
automatic = (Button) findViewById(R.id.button3);
manual = (Button) findViewById(R.id.button6);
message = (TextView) findViewById(R.id.textView1);
fourty.setText("40 Leds");
thirty.setText("30 Leds");
twenty.setText("20 Leds");
twelve.setText("12 Leds");
automatic.setText("Automatic");
manual.setText("Manual");
message.setText("Using this app you can take full control of the Luma Mini!" +
"When it's running on automatic please switch back to manual first before switching to other versions.");
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
fourty.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("a");
Toast msg = Toast.makeText(getBaseContext(),
"40 Leds version", Toast.LENGTH_SHORT);
msg.show();
}
});
thirty.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("b");
Toast msg = Toast.makeText(getBaseContext(),
"30 Leds version", Toast.LENGTH_SHORT);
msg.show();
}
});
twenty.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("c");
Toast msg = Toast.makeText(getBaseContext(),
"20 Leds version", Toast.LENGTH_SHORT);
msg.show();
}
});
twelve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("d");
Toast msg = Toast.makeText(getBaseContext(),
"12 Leds version", Toast.LENGTH_SHORT);
msg.show();
}
});
automatic.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("e");
Toast msg = Toast.makeText(getBaseContext(),
"Run automatically", Toast.LENGTH_SHORT);
msg.show();
}
});
manual.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("f");
Toast msg = Toast.makeText(getBaseContext(),
"Manually switch Leds", Toast.LENGTH_SHORT);
msg.show();
}
});
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...In onResume - Attempting client connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting to Remote...");
try {
btSocket.connect();
Log.d(TAG, "...Connection established and data link opened...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Creating Socket...");
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth Not supported. Aborting.");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth is enabled...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getBaseContext(),
title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Sending data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here's my Arduino script:
#include <SoftwareSerial.h>
#include <TimerOne.h>
#define Rx 2
#define Tx 3
#define seconds 4
char serialData; // Serial data memory
int counter1; // Overflow memory
int action; // Action trigger
int once = 0; // Run only once
SoftwareSerial Bluetooth(Rx, Tx);
void setup(){
pinMode(Tx, OUTPUT); // Configure Tx as OUTPUT (Transmitter)
pinMode(Rx, INPUT);
delay(1000);
Bluetooth.begin(9600);
Serial.begin(1200);
delay(1000);
Serial.print("Bluetooth ready");
Bluetooth.flush();
TimerOneSetup(); // Run the setup for Timer One
for(int i = 5; i <= 8; i++){ // Make pins 5, 6, 7 and 8 OUTPUT
pinMode(i, OUTPUT);
}
}
void interrupt1(){ // Timer One loop
counter1++; // Count the amount of seconds has passed
if (counter1 == seconds){ // Trigger the next action after a several amount of seconds (Default: 4 seconds)
action++;
counter1 = 0;
}
if (action > 3){ // Reset action trigger when after all actions were runned
action = 0;
}
}
void loop(){ // Endless loop
if (Serial.available()){ // Wait for data recieved from Local device
serialData = Serial.read(); // Put recieved data in memory
Serial.print("Data recieved from Local device: ");
Serial.println(serialData);
}
if (Bluetooth.available()){ // Wait for data recieved from Bluetooth device
serialData = Bluetooth.read(); // Put recieved data in memory
Serial.print("Data recieved from Bluetooth device: ");
Serial.print(serialData);
}
if (once == 0){ // This script will be run only once
serialData = 'e'; // Put switch on automatic on startup
once++; // Get into the next stage which may be run only once
}
switch(serialData){ // Perform action on state of the switch
case 'a':
fourtyLeds(); // Show the 40 Leds version of the Luma Mini
break;
case 'b':
thirtyLeds(); // Show the 30 Leds version of the Luma Mini
break;
case 'c':
twentyLeds(); // Show the 20 Leds version of the Luma Mini
break;
case 'd':
twelveLeds(); // Show the 12 Leds version of the Luma Mini
break;
case 'e':
while(serialData == 'e'){ // Keep changing different Led versions of the Luma Mini automatically
switch(action){
case 0: // Wait for the action trigger to hit the first action
fourtyLeds(); // Show the 40 Leds version of the Luma Mini
break;
case 1: // Wait for the action trigger to hit the second action
twelveLeds(); // Show the 12 Leds version of the Luma Mini
break;
case 2: // Wait for the action trigger to hit the third action
twentyLeds(); // Show the 20 Leds version of the Luma Mini
break;
case 4: // Wait for the action trigger to hit the fourth action
thirtyLeds(); // Show the 30 Leds version of the Luma Mini
break;}
if (Serial.read() == 'f'){ // Wait for data recieved from Local device
serialData = Serial.read(); // Put recieved data in memory
Serial.print("Data recieved from Local device: ");
Serial.println(serialData);
}
if (Bluetooth.read() == 'f'){ // Wait for data recieved from Bluetooth device
serialData = Bluetooth.read(); // Put recieved data in memory
Serial.print("Data recieved from Bluetooth device: ");
Serial.println(serialData);
}
break;
}
}
}
void BluetoothSetup(){
pinMode(Tx, OUTPUT); // Configure Tx as OUTPUT (Transmitter)
pinMode(Rx, INPUT); // Configure Rx as INPUT (Reciever)
Bluetooth.begin(9600); // Set Bluetooth baud rate to default baud rate 38400
Bluetooth.print("\r\n+STWMOD=0\r\n"); // Set the Bluetooth to work in slave mode
Bluetooth.print("\r\n+STNA=Luma Mini\r\n"); // Set Bluetooth name to Luma Mini
Bluetooth.print("\r\n+STOAUT=1\r\n"); // Permit paired device to connect
Bluetooth.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
delay(2000);
Bluetooth.print("\r\n+INQ=1\r\n"); // Make this Bluetooth Slave inquirable
Serial.println("The slave Bluetooth is inquirable!");
delay(2000);
Bluetooth.flush();
}
void TimerOneSetup(){
Timer1.initialize(1000000); // Initialize Timer One for an overflow exactly every 1 second
Timer1.attachInterrupt(interrupt1); // Open the Timer One loop
}
void fourtyLeds(){ // Show the 40 Leds version of the Luma Mini
for(int i = 5; i <= 8; i++){
digitalWrite(i, LOW);
}
}
void thirtyLeds(){ // Show the 30 Leds version of the Luma Mini
digitalWrite(5, HIGH);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
digitalWrite(8, LOW);
}
void twentyLeds(){ // Show the 20 Leds version of the Luma Mini
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, LOW);
digitalWrite(8, HIGH);
}
void twelveLeds(){ // Show the 12 Leds version of the Luma Mini
for (int i = 5; i <= 8; i++){
digitalWrite(i, HIGH);
}
}
My question: How can I send CHAR data from an Android Device to my Arduino? And what to edit on my script?
I have not gone through your code. But looking at the question, I suggests to keep Arduino FW coding away till Android app is tested and developed to a certain level. The way forward could be:
Disconnect HC-06 from other hardware.
Make a loopback connection at HC-06 (i.e Connect TX & RX outputs of HC-06 together.
Then Test your Android application. If app is receiving same as transmitted, then your android app is ok, and you can move on perfecting Arduino FW. Else, the android app needs to be perfected.
You can have a look at a similar question HC-05 bluetooth module on Arduino + Debugging .
Here's the code I use, and it works fine for me.
On the Android side, I'm only including my bluetooth file, which should be easy to fit into your app. It's main advantage is that after your app start it by calling btConnect(), everything else is automatic. It finds and connects to your "HC-06" without further "human intervention". And if you turn off the "HC-06", Android will continue watching for the "HC-06" to come back online, and will auto-connect to it again.
The Arduino Sketch sends a signal once each second. If 10 seconds are missed, the Android assumes the connection has been lost and re-enters connect mode.
ANDROID BLUETOOTH JAVA FILE:
package com.exercise.androidanimbuttons;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.IntentFilter;
import android.widget.Toast;
import android.bluetooth.BluetoothSocket;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.Set;
import android.os.Handler;
public class BlueTooth extends vars {
private Set<BluetoothDevice> pairedDevices;
String address = null;
private ProgressDialog progress = null;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
InputStream mmInStream = null;
private Handler myHandler = new Handler();
byte[] buffer = new byte[25];
int readBytes;
files filesI = new files();
Handler btH = new Handler();
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private SingBroadcastReceiver mReceiver;
Runnable btSearch;
void stopDiscovery() {
if (myBluetooth.isDiscovering()){
myBluetooth.cancelDiscovery();
}
}
void findCurrentBT() {
if (!myBluetooth.isEnabled()){
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, 0xDEADBEEF);
}
if (myBluetooth.isDiscovering()){
myBluetooth.cancelDiscovery();
}
closeProgress();
progress = ProgressDialog.show(BlueTooth.this, "Searching for headband...",
"MAKE SURE THE HEADBAND IS TURNED ON.");
progress.setCanceledOnTouchOutside(true);
myBluetooth.startDiscovery();
mReceiver = new SingBroadcastReceiver();
IntentFilter ifilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, ifilter);
checkSearch();
}
private class SingBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String derp = device.getName() + " - " + device.getAddress();
ta(derp);
Toast.makeText(context, derp, Toast.LENGTH_LONG);
if ((device.getName() != null) &&
(device.getName().indexOf("HC-06") == 0) &&
(device.getName().length() == 5))
{
myBluetooth.cancelDiscovery();
address = device.getAddress();
new ConnectBT().execute();
}
}
}
}
private Runnable readBT = new Runnable() {
public void run() {
int i;
int twoByte = 0;
short high = 0, low = 0;
try {
if (mmInStream.available() > 3) {
cnt = 0;
readBytes = mmInStream.read(buffer);
String S = "";
for (i = 0; i < 2; i++)
S += String.format("%03d", buffer[i] & 0xFF)+", ";
high = (short)(buffer[3] & 0xFF);
low = (short)(buffer[2] & 0xFF);
twoByte = ((high << 8) | low);
S += String.format("%03d", twoByte) + "\r\n";
filesI.writeALine("nights","data12.txt",S);
ta(S);
}
} catch (IOException e) {
ta("err:2 " + e.toString());
}
if (btSocket.isConnected())
myHandler.postDelayed(this, 100);
}
};
public void btConnect() {
Disconnect();
findCurrentBT();
}
public void btOn() {
turnOnLed();
}
public void btOff() { turnOffLed(); }
public void btDisconnect() { Disconnect(); }
private void Disconnect()
{
if (btSocket!=null)
{
try
{
btSocket.close();
}
catch (IOException e)
{ msg("Bluetooth Disconnect Error");}
}
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TF".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
int len;
byte[] buffer = new byte[400];
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TO".toString().getBytes());
len = btSocket.getInputStream().available();
btSocket.getInputStream().read(buffer,0,len);
}
catch (IOException e)
{
msg("Error");
}
}
}
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
void closeProgress() {
if (progress != null)
progress.dismiss();
}
private class ConnectBT extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
closeProgress();
progress = ProgressDialog.show(BlueTooth.this, "Connecting to headband...",
"");
progress.setCanceledOnTouchOutside(true);
}
#Override
protected Void doInBackground(Void... devices)
{
try
{
if (btSocket == null || (!btSocket.isConnected()))
{
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();
}
}
catch (IOException e) { }
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if (!btSocket.isConnected())
{
msg("Connection Failed. Is the headband turned on?");
}
else
{
msg("Connected.");
try {
mmInStream = btSocket.getInputStream();
myHandler.postDelayed(readBT, 1000);
} catch (IOException e) {
ta("err:1 " + e.toString());
}
}
closeProgress();
}
}
int cnt = 0;
void checkSearch() {
if (btSearch != null)
return;
btSearch = new Runnable(){#Override public void run(){
if ((btSocket != null) && (btSocket.isConnected())) {
cnt--;
if (cnt < -10) {
cnt = 0;
btConnect();
}
} else if (myBluetooth.isDiscovering()) {
cnt++;
}
btH.postDelayed(this, 1000);
fa(cnt);
}};
btH.postDelayed(btSearch,1000);
}
}
MATCHING ARDUINO SKETCH:
byte mini [4];
int battery;
unsigned long mill = millis();
byte moveCnt = 1;
int minuteCnt = 0;
int lastMove = 0;
int moveA, moveB, moveC, LMoveA, LMoveB, LMoveC, totMove, eyes, LEyes, totEyes;
int moveUpA = 0;
int moveDnA = 1000;
int moveUpB = 0;
int moveDnB = 1000;
int moveUpC = 0;
int moveDnC = 1000;
#include <SoftwareSerial.h>
SoftwareSerial mySerial(3, 5); // RX, TX
void setup()
{
Serial .begin(9600);
mySerial.begin(9600);
}
void loop()
{
if (millis() > mill)
{
mill += 100;
minuteCnt++;
// *** EYES ***
eyes = analogRead(A6);
totEyes += abs(eyes-LEyes);
LEyes = eyes;
// *** MOVEMENT *** --KEEP-- moveA = max(0,analogRead(A1) >> 2);
moveA = analogRead(A0);
moveB = analogRead(A1);
moveC = analogRead(A2);
totMove += abs(moveA-LMoveA) + abs(moveB-LMoveB) + abs(moveC-LMoveC);
LMoveA = moveA; LMoveB = moveB; LMoveC = moveC;
// *** SEND SECOND ***
if (minuteCnt >= 10)
{
minuteCnt = 0;
// *** BATTERY ***
battery = analogRead(A5); // battery
mini[2] = (battery & 0xff); // battery low byte
mini[3] = ((battery >> 8) & 0xff); // battery high byte
// *** EYES ***
mini[0] = min(max(0,totEyes-10),255);
totEyes = 0;
// *** MOVEMENT ***
mini[1] = min(max(0,totMove-30),255);
totMove = 0;
Serial.print(mini[0]);
Serial.print(" ");
Serial.print(mini[1]);
Serial.print(" ");
Serial.print(mini[2]);
Serial.print(" ");
Serial.println(mini[3]);
mySerial.write(mini,4);
}
}
}
I'm trying to implement a class to discover services on the network.
I've tried working with Android's NSD and it does discover the services fine, but it supports only API levels 16 and up, and I can't seem to retrieve the txtRecord field within the service info (it returns null for some reason). Turns out it's a known problem...
So now I'm trying to work with jmDNS, which doesn't seem to find services at all.
here's my class (I'm working with the AndroidAnnotations framework) MDnsHelper:
#EBean
public class MDnsHelper implements ServiceListener {
public static final String SERVICE_TYPE = "_http._tcp.local";
Activity activity;
private JmDNS jmdns;
private MulticastLock multicastLock;
WifiManager wm;
InetAddress bindingAddress;
boolean isDiscovering;
public void init(Activity activity) {
this.activity = activity;
isDiscovering = false;
wm = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
multicastLock = wm.createMulticastLock(activity.getPackageName());
multicastLock.setReferenceCounted(false);
}
#Background
public void startDiscovery() {
if (isDiscovering)
return;
System.out.println("starting...");
multicastLock.acquire();
try {
System.out.println("creating jmdns");
jmdns = JmDNS.create();
System.out.println("jmdns created");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (jmdns != null) {
jmdns.addServiceListener(SERVICE_TYPE, MDnsHelper.this);
isDiscovering = true;
System.out.println("discovering services of type: " + SERVICE_TYPE);
}
}
}
#Background
public void stopDiscovery() {
if (!isDiscovering || jmdns == null)
return;
System.out.println("stopping...");
multicastLock.release();
jmdns.removeServiceListener(SERVICE_TYPE, MDnsHelper.this);
System.out.println("listener for " + SERVICE_TYPE + " removed");
try {
jmdns.close();
isDiscovering = false;
System.out.println("jmdns closed");
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void serviceAdded(ServiceEvent service) {
System.out.println("found: " + service.getInfo().toString());
}
#Override
public void serviceRemoved(ServiceEvent service) {
System.out.println("lost: " + service.getInfo().toString());
}
#Override
public void serviceResolved(ServiceEvent service) {
System.out.println("resolved: " + service.getInfo().toString());
}
}
And in my app I call:
init(getActivity());
And then startDiscovery(); to start scanning and stopDiscovery(); to stop scanning.
And of course, I gave the app the required permissions in the manifest...
What am I missing here?
If you need me to provide additional code/info - just ask.
thanks!!
I am the author of ZeroConf Browser for Android and I use the open source Library JmDNS for all my resolving. It works great but there are a few tricks to getting it to work properly.
In your Android manifest.xml make sure you have these permissions at least.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
Before starting the activity you must allow multi-cast packets by acquiring a multicast lock.
#Override
protected void onStart() {
Log.i(TAG, "Starting ServiceActivity...");
super.onStart();
try {
Log.i(TAG, "Starting Mutlicast Lock...");
WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
// get the device ip address
final InetAddress deviceIpAddress = getDeviceIpAddress(wifi);
multicastLock = wifi.createMulticastLock(getClass().getName());
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
Log.i(TAG, "Starting ZeroConf probe....");
jmdns = JmDNS.create(deviceIpAddress, HOSTNAME);
jmdns.addServiceTypeListener(this);
} catch (IOException ex) {
Log.e(TAG, ex.getMessage(), ex);
}
Log.i(TAG, "Started ZeroConf probe....");
}
private InetAddress getDeviceIpAddress(WifiManager wifi) {
InetAddress result = null;
try {
// default to Android localhost
result = InetAddress.getByName("10.0.0.2");
// figure out our wifi address, otherwise bail
WifiInfo wifiinfo = wifi.getConnectionInfo();
int intaddr = wifiinfo.getIpAddress();
byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff),
(byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };
result = InetAddress.getByAddress(byteaddr);
} catch (UnknownHostException ex) {
Log.w(TAG, String.format("getDeviceIpAddress Error: %s", ex.getMessage()));
}
return result;
}
And don't forget on stopping the scan to unlock the multicast lock and shut down JmDNS.
#Override
protected void onStop() {
Log.i(TAG, "Stopping ServiceActivity...");
super.onStop();
stopScan();
}
private static void stopScan() {
try {
if (jmdns != null) {
Log.i(TAG, "Stopping ZeroConf probe....");
jmdns.unregisterAllServices();
jmdns.close();
jmdns = null;
}
if (multicastLock != null) {
Log.i(TAG, "Releasing Mutlicast Lock...");
multicastLock.release();
multicastLock = null;
}
} catch (Exception ex) {
Log.e(TAG, ex.getMessage(), ex);
}
}
Most importanty don't use the default constructor. You must use the IP Address Constructor. I noticed in your code you are just doing JmDNS.create(). I think for some reason the only way it works on Android is to use the contructor below.
jmdns = JmDNS.create(deviceIpAddress, HOSTNAME);
If you are having this error in Android Oreo 8.x, this might help you.
First, Remember to make sure you have added these permissions into your Android manifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
Acquire a multicast lock to allow multi-cast packets.
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
MulticastLock lock = wifi.createMulticastLock("jmdns-multicast-lock");
lock.setReferenceCounted(true);
lock.acquire();
Now, use only this constructor JmDNS.create(InetAddress addr, String name) to create an instance of JmDNS and bind it to a specific network interface given its IP-address, like this:
try {
jmDNS = JmDNS.create(InetAddress.getByName(obtainIPv4Address(info)), HOST_NAME);
} catch (IOException e) {
LogHelper.e(TAG, "Error in JmDNS creation: " + e);
}
Finally, just make sure to call JmDNSunreisterAllServices(), and JmDNS.close() to stop JmDNS stream and releases any system resources associated with it. Also, call MulticastLock.release() to unlock the multicast lock when you're done with it.
try {
if (jmDNS != null) {
jmDNS.unregisterAllServices();
jmDNS.close();
jmDNS = null;
}
if (lock != null) {
lock.release();
lock = null;
}
} catch (Exception e) {
e.printStackTrace();
}
How to use 3G Connection in Android Application instead of Wi-fi?
I want to connect a 3G connection, is there any sample code to connect to 3G instead of Wi-fi?
/**
* Enable mobile connection for a specific address
* #param context a Context (application or activity)
* #param address the address to enable
* #return true for success, else false
*/
private boolean forceMobileConnectionForAddress(Context context, String address) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null == connectivityManager) {
Log.debug(TAG_LOG, "ConnectivityManager is null, cannot try to force a mobile connection");
return false;
}
//check if mobile connection is available and connected
State state = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
Log.debug(TAG_LOG, "TYPE_MOBILE_HIPRI network state: " + state);
if (0 == state.compareTo(State.CONNECTED) || 0 == state.compareTo(State.CONNECTING)) {
return true;
}
//activate mobile connection in addition to other connection already activated
int resultInt = connectivityManager.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableHIPRI");
Log.debug(TAG_LOG, "startUsingNetworkFeature for enableHIPRI result: " + resultInt);
//-1 means errors
// 0 means already enabled
// 1 means enabled
// other values can be returned, because this method is vendor specific
if (-1 == resultInt) {
Log.error(TAG_LOG, "Wrong result of startUsingNetworkFeature, maybe problems");
return false;
}
if (0 == resultInt) {
Log.debug(TAG_LOG, "No need to perform additional network settings");
return true;
}
//find the host name to route
String hostName = StringUtil.extractAddressFromUrl(address);
Log.debug(TAG_LOG, "Source address: " + address);
Log.debug(TAG_LOG, "Destination host address to route: " + hostName);
if (TextUtils.isEmpty(hostName)) hostName = address;
//create a route for the specified address
int hostAddress = lookupHost(hostName);
if (-1 == hostAddress) {
Log.error(TAG_LOG, "Wrong host address transformation, result was -1");
return false;
}
//wait some time needed to connection manager for waking up
try {
for (int counter=0; counter<30; counter++) {
State checkState = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
if (0 == checkState.compareTo(State.CONNECTED))
break;
Thread.sleep(1000);
}
} catch (InterruptedException e) {
//nothing to do
}
boolean resultBool = connectivityManager.requestRouteToHost(ConnectivityManager.TYPE_MOBILE_HIPRI, hostAddress);
Log.debug(TAG_LOG, "requestRouteToHost result: " + resultBool);
if (!resultBool)
Log.error(TAG_LOG, "Wrong requestRouteToHost result: expected true, but was false");
return resultBool;
}
And this for calculate host address:
/**
* This method extracts from address the hostname
* #param url eg. http://some.where.com:8080/sync
* #return some.where.com
*/
public static String extractAddressFromUrl(String url) {
String urlToProcess = null;
//find protocol
int protocolEndIndex = url.indexOf("://");
if(protocolEndIndex>0) {
urlToProcess = url.substring(protocolEndIndex + 3);
} else {
urlToProcess = url;
}
// If we have port number in the address we strip everything
// after the port number
int pos = urlToProcess.indexOf(':');
if (pos >= 0) {
urlToProcess = urlToProcess.substring(0, pos);
}
// If we have resource location in the address then we strip
// everything after the '/'
pos = urlToProcess.indexOf('/');
if (pos >= 0) {
urlToProcess = urlToProcess.substring(0, pos);
}
// If we have ? in the address then we strip
// everything after the '?'
pos = urlToProcess.indexOf('?');
if (pos >= 0) {
urlToProcess = urlToProcess.substring(0, pos);
}
return urlToProcess;
}
/**
* Transform host name in int value used by {#link ConnectivityManager.requestRouteToHost}
* method
*
* #param hostname
* #return -1 if the host doesn't exists, elsewhere its translation
* to an integer
*/
private static int lookupHost(String hostname) {
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
return -1;
}
byte[] addrBytes;
int addr;
addrBytes = inetAddress.getAddress();
addr = ((addrBytes[3] & 0xff) << 24)
| ((addrBytes[2] & 0xff) << 16)
| ((addrBytes[1] & 0xff) << 8 )
| (addrBytes[0] & 0xff);
return addr;
}
And following permission must be added to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
It works only with android 2.2 and above, tested on both Nexus One and on LG Optimus, other phones I don't know because some method of ConnectivityMananger are vendor-specific.
After 15-20 seconds of inactivity, mobile network is automatically disconnected.
The T-Mobile 'My Account" app does this, if you are connected to a WiFi connection it tells you that their program will not work over WiFi and then asks the user if they want to turn off the WiFi connection. If you choose "No" then the application exits, if you choose "Yes" then the app turns off your WiFi connection and then continues with starting up.
I think this is a good model to follow, it will ensure that your app is not being ran over WiFi and allows the user to decide if they want to turn off WiFi or not. An improvement on this model would be to turn wifi back on when the user navigates away from your app.
I haven't tested the following code, but it looks like it should work (modified from here)
use the following permissions in your manifest
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
and here is some actual code to turn wifi on/off
private WifiManager wifiManager;
#Override
public void onCreate(Bundle icicle)
{
....................
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if(wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
}
else
{
wifiManager.setWifiEnabled(true);
}
}
If you do not want to go down that route it looks like you might be able to tell the phone that you would prefer to use the mobile data network rather than the wifi network.
The Android ConnectivityManager offers a function setNetworkPreference. This function is not really documented as you can tell if you click the link. I would paly around with it though because the constants that are defined seem to hint that you can set this to either TYPE_MOBILE or TYPE_WIFI and there is a DEFAULT_NETWORK_PREFERENCE constant as well that is defined as being 0x00000001 which is the same as TYPE_WIFI. So try getting access to a ConnectivityManager by calling
Context.getSystemService(Context.CONNECTIVITY_SERVICE);
and then try using the setNetworkPreference() function.
It doesn't appear to require any permissions in the manifest but it might require the CHANGE_NETWORK_STATE permission or something along those lines.
If you do sue the setNetworkPreference function it would probably be best to also set the Network Preference back to its original values (received from getNetworkPreference)
I hope this helps.
I think that is not possible from Java. The system shuts down all mobile network based communication if connected to a wireless network. I think that you aren't allowed to start a 3G connection from you program.
Here is the code that works on API 21+ (Lollipop, Marshmallow..).
I prefer to use OkHttp with Network.getSocketFactory(), but Network.openURLConnection() also works fine.
private void doTest()
{
display("Requesting CELLULAR network connectivity...");
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
connectivityManager.requestNetwork(request, new ConnectivityManager.NetworkCallback()
{
/**
* Called when the framework connects and has declared a new network ready for use.
* This callback may be called more than once if the {#link Network} that is
* satisfying the request changes.
*
* This method will be called on non-UI thread, so beware not to use any UI updates directly.
*
* #param network The {#link Network} of the satisfying network.
*/
#Override
public void onAvailable(final Network network)
{
display("Got available network: " + network.toString());
try
{
final InetAddress address = network.getByName("navalclash.com");
display("Resolved host2ip: " + address.getHostName() + " -> " + address.getHostAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
display("Do request test page from remote http server...");
if(okHttpClient == null)
{
okHttpClient = new OkHttpClient.Builder().socketFactory(network.getSocketFactory()).build();
}
Request request = new Request.Builder()
.url("http://navalclash.com")
.build();
try (Response response = okHttpClient.newCall(request).execute())
{
display("RESULT:\n" + response.body().string());
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
}
Inspired by code in this ticket and using some parts of it, here is service that establishes hipri mobile and keeps it running.
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicBoolean;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.IBinder;
import android.util.Log;
public class HipriService extends Service {
private AtomicBoolean enabledMobile = new AtomicBoolean(false);
public boolean enableMobileConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (null == cm) {
Log.d(TAG, "ConnectivityManager is null, cannot try to force a mobile connection");
return false;
}
/*
* Don't do anything if we are connecting. On the other hands re-new
* connection if we are connected.
*/
State state = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
Log.d(TAG, "TYPE_MOBILE_HIPRI network state: " + state);
if (0 == state.compareTo(State.CONNECTING))
return true;
/*
* Re-activate mobile connection in addition to other connection already
* activated
*/
int resultInt = cm.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableHIPRI");
//Log.d(TAG, "startUsingNetworkFeature for enableHIPRI result: " + resultInt);
//-1 means errors
// 0 means already enabled
// 1 means enabled
// other values can be returned, because this method is vendor specific
if (-1 == resultInt) {
Log.e(TAG, "Wrong result of startUsingNetworkFeature, maybe problems");
return false;
}
if (0 == resultInt) {
Log.d(TAG, "No need to perform additional network settings");
return true;
}
return requestRouteToHost(this, Uploader.ServerAddress);
}
private Thread pingerThread = null;
private void startMobileConnection() {
enabledMobile.set(true);
pingerThread = new Thread(new Runnable() {
#Override
public void run() {
while (enabledMobile.get()) {
/*
* Renew mobile connection. No routing setup is needed. This
* should be moved to 3g monitoring service one day.
*/
enableMobileConnection();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
}
}
});
pingerThread.start();
}
private void stopMobileConnection() {
enabledMobile.set(false);
disableMobileConnection();
pingerThread.interrupt();
pingerThread = null;
}
public void disableMobileConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
cm.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableHIPRI");
}
public final static int inetAddressToInt(InetAddress inetAddress) {
byte[] addrBytes;
int addr;
addrBytes = inetAddress.getAddress();
addr = ((addrBytes[3] & 0xff) << 24) | ((addrBytes[2] & 0xff) << 16) | ((addrBytes[1] & 0xff) << 8)
| (addrBytes[0] & 0xff);
return addr;
}
public final static InetAddress lookupHost(String hostname) {
try {
return InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
return null;
}
}
private boolean requestRouteToHost(Context context, String hostname) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (null == cm) {
Log.d(TAG, "ConnectivityManager is null, cannot try to force a mobile connection");
return false;
}
/* Wait some time needed to connection manager for waking up */
try {
for (int counter = 0; enabledMobile.get() && counter < 30; counter++) {
State checkState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
Log.i(TAG, "Waiting for mobile data on. State " + checkState);
if (0 == checkState.compareTo(State.CONNECTED))
break;
Thread.sleep(1000);
}
} catch (InterruptedException e) {
//nothing to do
}
if (!enabledMobile.get()) {
Log.d(TAG, "Mobile data is turned off while waiting for routing.");
return false;
}
State checkState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
if (0 != checkState.compareTo(State.CONNECTED)) {
Log.e(TAG, "Mobile data is still turned off after 30 sec of waiting.");
return false;
}
Log.i(TAG, "Adding routing for " + hostname);
InetAddress inetAddress = lookupHost(hostname);
if (inetAddress == null) {
Log.e(TAG, "Failed to resolve " + hostname);
return false;
}
int hostAddress = inetAddressToInt(inetAddress);
boolean resultBool = cm.requestRouteToHost(ConnectivityManager.TYPE_MOBILE_HIPRI, hostAddress);
Log.d(TAG, "requestRouteToHost result: " + resultBool);
if (!resultBool)
Log.e(TAG, "Wrong requestRouteToHost result: expected true, but was false");
return resultBool;
}
#Override
public void onCreate() {
super.onCreate();
startMobileConnection();
}
#Override
public void onDestroy() {
stopMobileConnection();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Here is how I start/stop it when needed. Note that it also gets locks on cpu and wifi so that it may run when the phone sleeps (screen only). Wifi is needed because my app is kind of bridge between wifi and mobile connections. You may not need it.
public void startMobileData() {
if (!enabledMobile.get()) {
enabledMobile.set(true);
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "Wifi Wakelock");
wifiLock.acquire();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
partialLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "3G Wakelock");
partialLock.acquire();
startService(new Intent(this, HipriService.class));
}
}
public void stopMobileData() {
if (enabledMobile.get()) {
enabledMobile.set(false);
Log.i(TAG, "Disabled mobile data");
stopService(new Intent(this, HipriService.class));
if (partialLock != null) {
partialLock.release();
partialLock = null;
}
if (wifiLock != null) {
wifiLock.release();
wifiLock = null;
}
}
}
Don't forget to add service to you manifest file.
Use connection manager and set network preference as you want.
for example:
dataManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
dataManager.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);
This aplication activate 3G and Wifi connection, Giving preference to 3G!!
Very useful http://www.redrails.com.br/2012/02/wireless-analyzer-for-android/
#umka
i think, app can only reach to those hosts through HIPRI which it has requested, may be for other hosts(whose routes are not requested) is using the default network(MOBILE or WIFI).
On calling stopUsingNetworkFeature(), It will check -- is there any other app is using this network, if yes, then it will ignore your request to down this network feature.
one of the main purpose of HIPRI network is that - if wifi is on and an app wants to use mobile netwrok(3G)to reach the particular host, it can reach through HIPRI network.
There is a missing piece of code on #Northern Captain answer, the DNS lookup code.
Here is a working code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.d("NetworkDns", "Requesting CELLULAR network connectivity...");
NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
connectivityManager.requestNetwork(request, new ConnectivityManager.NetworkCallback()
{
#Override
public void onAvailable(final Network network)
{
Log.d("NetworkDns", "Got available network: " + network.toString());
try
{
final InetAddress address = network.getByName("www.website.com");
Log.d("NetworkDns", "Resolved host2ip: " + address.getHostName() + " -> " + address.getHostAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
Log.d("NetworkDns", "Do request test page from remote http server...");
OkHttpClient okHttpClient = null;
if(okHttpClient == null)
{
okHttpClient = new OkHttpClient.Builder()
.socketFactory(network.getSocketFactory())
.dns(new Dns() {
#Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
if (network != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
List<InetAddress> addresses = Arrays.asList(network.getAllByName(hostname));
Log.d("NetworkDns", "List : " + addresses);
return addresses;
}
return SYSTEM.lookup(hostname);
}
}).build();
}
Request request = new Request.Builder()
.url("http://www.website.com")
.build();
try (Response response = okHttpClient.newCall(request).execute())
{
Log.d("NetworkDns", "RESULT:\n" + response.body().string());
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
}