We have developed an android application-just to on the wi-fi service of the smartphone and then connect to a java server running on a different pc.The client code is using the IP address of that particular pc on which the server is running.The client code is also using the same port number as the server code.But still the client socket is not connecting to the particular server or rather not responding at all.
My client code :
JAVA File :
package com.example.android.try1;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class First extends AppCompatActivity {
Button bt1;
TextView smsg;
ObjectOutputStream oos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
Button bt1 = (Button)findViewById(R.id.bt1);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WifiManager wifi = (WifiManager)
getApplicationContext().getSystemService(Context.WIFI_SERVICE);
final boolean b = wifi.setWifiEnabled(true);
Socket clientSocket = null;
try {
Log.d("Initializing client","");
clientSocket = new Socket("192.168.43.193", 6666);
if (clientSocket!=null)
{
Log.d("Tested","connected");
oos = new ObjectOutputStream(clientSocket.getOutputStream());
oos.writeUTF("hii");
oos.close();
}
else
{
Log.d("Client Socket","NULL");
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
getApplicationContext().getSystemService(Context.WIFI_SERVICE);
final boolean b = wifi.setWifiEnabled(true);
is async an operation and takes some time to connect to available wifi network
So once you switch on the wifi you need to wait for network connection then try to connect.
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
You should register for network change broadcast and once you get broadcast check for connection and then connect to your server
Related
I am creating app that sends joystick data via UDP to my ESP32 at 192.168.4.1:1234 and whenever i try to send any data it crashes.
Crash Log:
2022-09-06 17:22:38.864 15388-15388/com.example.drnecontroller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.drnecontroller, PID: 15388
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1668)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getByName(InetAddress.java:1106)
at com.example.drnecontroller.MainActivity.lambda$onCreate$0(MainActivity.java:44)
at com.example.drnecontroller.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7441)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7418)
at android.view.View.access$3700(View.java:835)
at android.view.View$PerformClick.run(View.java:28676)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
2022-09-06 17:22:38.911 393-393/? E/BpTransactionCompletedListener: Failed to transact (-32)
Client script:
package com.example.drnecontroller;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
public class MainActivity extends AppCompatActivity {
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.SubmitButton);
TextView IPAddrShow = (TextView) findViewById(R.id.IPAddressShow);
button.setOnClickListener(view -> {
try {
int port = 1234;
byte[] MSG;
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress IP = InetAddress.getByName("localhost");
MSG = "HELLO".getBytes();
DatagramPacket datagramPacket = new DatagramPacket(MSG, MSG.length,IP,port);
datagramSocket.send(datagramPacket);
IPAddrShow.setText("Sent");
} catch(IOException e){
e.printStackTrace();
}
});
}
}
On android, you cannot use network from the UI thread.
All you have to do is to send your data from an other thread. I recommend using an executor.
For example by wrapping your code in a Runnable :
ExecutorService executor= Executors.newFixedThreadPool(1);
executor.submit(yourRunnable);
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.OkHttpClient;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final TextView textView = findViewById(R.id.text_view_id);
final String IMAGE1 = "storage/emulated/0/Download/image_1.jpeg";
File file1 = new File(IMAGE1);
try {
final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("images", "image_1.jpeg",
RequestBody.create(file1, MEDIA_TYPE_JPEG))
.addFormDataPart("organs", "flower")
.build();
Request request = new Request.Builder()
.url("https://my-api.plantnet.org/v2/identify/all?api-key=123")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
textView.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I understand that I'm trying to run a network activity here on the main thread. That's why I included the StrictMode permitAll thing to get around the issue (I saw an answer to a similar topic that suggested doing so). I am trying to use the PlantNet API here and I use my phone for testing. The same phone where the image is saved.
go see retrofit
it provides a nice and easy way to make your network calls off the main thread
I am trying to write an app that pings a web page, which will then trigger an action.
package com.anton.lightcontrol;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Switch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
Switch onOffSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onOffSwitch = (Switch) findViewById(R.id.onOffSwitch);
onOffSwitch.setChecked(true);
onOffSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onOffSwitch.isChecked()==true) {
onOffSwitch.setTextColor(Color.GREEN);
LightConnection("http://raspberrypi/toggle_on.py");
}
else if (onOffSwitch.isChecked()==false){
onOffSwitch.setTextColor(Color.RED);
LightConnection("http://raspberrypi/toggle_off.py");
}
}
});
}
private void LightConnection(final String accessUrl){
(new Thread(new Runnable() {
#Override
public void run() {
try{
Log.d("EXEC", "#1");
URL url = new URL(accessUrl);
Log.d("EXEC", "#2");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Log.d("EXEC", "#3");
InputStreamReader input = new InputStreamReader(conn.getInputStream(), "utf-8");
Log.d("EXEC", "#4");
BufferedReader reader = new BufferedReader(input,2000);
Log.d("EXEC", "#5");
String line = reader.readLine();
Log.d("EXEC", "#6");
}
catch (IOException e){
Log.d("EXEC", "#10 - CATCH");
onOffSwitch.setTextColor(Color.YELLOW);
}
}
})).start();
}
}
My debug output looks like the following:
D/EXEC: #1
D/EXEC: #2
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/EXEC: #3
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/EXEC: #10 - CATCH
I have been searching for a solution for the isSBSettingEnabled false error, but I couldn't find anything that helped me.
I am running my app on a Samsung M20 smartphone.
This technically isn't an error, since it's alerting you that you're not using a network security config. More information on this here: Network security configuration: Android Developer Docs.
However, if you're limited to using HTTP, you can resolve connection issues by permitting cleartext traffic by adding this to your <application> tag in AndroidManifext.xml:
android:usesCleartextTraffic="true"
I have been trying to get some very simple code to work which should read an online file and print the contents of that file in the log. At first I didn't know that it needed to be handled in a seperate thread so I left it in the onCreate Method. Now I put it into a seperate Thread with the help of this question: How to use separate thread to perform http requests but the app still crashes! Since I'm desperate to get this working so I can keep on learning how to program this app, I will insert the exact code I used:
package com.dan6erbond.schoolhelper;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private String link = "https://dan6erbond.github.io/I1A/Documents/Zusammenfassungen/Zusammenfassungen.json";
String content;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
Log.i("TAG", content);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread downloadFile = new Thread(new Runnable(){
#Override
public void run(){
try {
URL url = new URL(link);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
content += str;
}
Log.i("TAG", content);
in.close();
} catch (Exception e) {
Log.i("TAG", "Error occured!");
}
handler.sendEmptyMessage(0);
}
});
downloadFile.start();
}
}
In the log the error message is being sent:
01-05 07:40:33.320 9601-9622/com.dan6erbond.schoolhelper I/TAG: Error occured!
I'd be really happy if someone could help me with this problem. It's probably very simple but I just started coding in Android Studio so I'm really new to this.
I just needed to add the INTERNET permission. I figured that out by printing the error message:
Log.i("TAG", e.getMessage());
Which resulted in this:
01-05 08:05:10.806 11815-11838/com.dan6erbond.schoolhelper I/TAG: Permission denied (missing INTERNET permission?)
I just added this to the Android Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
Thanks everyone for your help!
I am working on a project where I have to connect my android device to a GPS with usb. I can't figure out how I can get the data out of my GPS and I do not want to use the device it's internall GPS because I need to be pretty accurate. I have read the tutorial on the android website and I have tried to work with it but I still do not understand how I have to make connection to the GPS.
Here is my code.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.util.HashMap;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
UsbDevice device = deviceList.get("deviceName");
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)){
if(device != null){
//roep hier de method aan om communicatie met he apparaat te maken
}
}
else{
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
}
}
You might want to give this a shot: http://code.google.com/p/usb-serial-for-android/. Captures all serial data, does not require rooting. You would need to use Service. Let us know if you need more help. I have done this before, not on Android though.