how to send data (a string) to a paired device in android? - android

I am working on bluetooth for the first time. I got the list of paired devices. Now my requirement is I need to send some data (a string) to the device. how can I do that? I tried searching but didn't find anything useful. Could anyone help out this?

Something like this might suffice:
DataOutputStream os;
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
BluetoothDevice remoteDevice;
remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(getApplicationContext(), "Discovered: " + remoteDeviceName + " address " + remoteDevice.getAddress(), Toast.LENGTH_SHORT).show();
try{
BluetoothDevice device = bluetooth.getRemoteDevice(remoteDevice.getAddress());
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
BluetoothSocket clientSocket = (BluetoothSocket) m.invoke(device, 1);
clientSocket.connect();
os = new DataOutputStream(clientSocket.getOutputStream());
new clientSock().start();
} catch (Exception e) {
e.printStackTrace();
Log.e("BLUETOOTH", e.getMessage());
}
}
};
registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
bluetooth.enable();
if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}
public class clientSock extends Thread {
public void run () {
try {
os.writeBytes("anything you want"); // anything you want
os.flush();
} catch (Exception e1) {
e1.printStackTrace();
return;
}
}
}
You will also need a lot of imports such as these:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.UUID;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
note that not all imports are necessary for this example code, your IDE might help you to sort them out for you.
Pass data on the os.writeBytes("anything you want"); // anything you want line.
You will also need Permissions

Related

How to return variables from AsyncTask to Google Map activity in Android

I have an async task that fetches a JSON array from a url and then parses it to a String.
My problem is that i cannot move the fetched data from URL to my Google Maps activity (Map Activity). When i tried Intent in Asynctask i could not make it.
Please help!! Thanks in advance
Async Task:
package com.example.panos.fleet_management;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import static android.app.PendingIntent.getActivity;
import static android.content.ContentValues.TAG;
import static android.support.v4.content.ContextCompat.startActivity;
/**
* Created by panos on 18/8/2018.
*/
public class MapRequest extends AsyncTask<Void,Void, Void> {
String data="";
String dataParsed="";
String singleParsed="";
double lon[],lat[];
String reg;
private Context context;
public MapRequest(Context context){
this.context=context;
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url= new URL("xxx.xxx");
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream= httpURLConnection.getInputStream() ;
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line= "";
while(line != null) {
line = bufferedReader.readLine();
data=data + line;
}
JSONArray JA=new JSONArray(data);
for (int i=0;i<JA.length();i++){
JSONObject JO= (JSONObject) JA.get(i);
singleParsed="Registration:"+ JO.get("Registration") + "\n"+
"Longitude:"+ JO.get("Longitude") + "\n"+
"Latitude:"+ JO.get("Latitude") + "\n";
dataParsed= dataParsed + singleParsed + "\n";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent(context, MapActivity.class);
intent.putExtra("dat",dataParsed);
}
}
JSON File
[{
"Registration": "YHB6595",
"Longitude": "11.00000000",
"Latitude": "3.00000000"
}, {
"Registration": "YMK3540",
"Longitude": "41.00000000",
"Latitude": "2.00000000"
}]
Map Activity :
package com.example.panos.fleet_management;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Map;
import java.util.Map.Entry;
import static com.example.panos.fleet_management.R.id.map;
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
new MapRequest(this).execute();
}
#Override
public void onMapReady (GoogleMap googleMap){
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(40,41);
LatLng location2 = new LatLng(11,41);
mMap.addMarker(new MarkerOptions().position(sydney).title(getIntent().getStringExtra("dat")));
mMap.addMarker(new MarkerOptions().position(location2).title("dsader"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
First, why you have the Volley imports and you're not using them? It's a very simple way to get data from network asynchronously, without the AsyncTask and right from your Activity.
Also you're creating the Intent and doing nothing with it. If you insist in using it the way you are, use the Intent to send a LocalBroadcastManager and register the receiver for it in your activity where the map is
At last I found a very simple answer to my question. The only thing that i needed to do was to make mMap variable public static and then access it from onPostexecute and put the data there.

Taking screenshot crashes app

I tried creating a screenshot app, but somehow I can not get the root content.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
public class Screenshot extends Activity {
public final String TAG = "Screen";
String output;
public String takeScreen(String savepathname) {
Log.e(TAG, "TAKESCREEN 01");
//View content = findViewById(R.id.button1);
//View content = findViewById(R.id.layoutroot);
//View content = getWindow().getDecorView().findViewById(android.R.id.content);
Log.e(TAG, "TAKESCREEN 01.5");
content.setDrawingCacheEnabled(true);
Log.e(TAG, "TAKESCREEN 02");
//View content = findViewById(R.id.layoutroot);
Bitmap bitmap = content.getDrawingCache();
File file = new File( Environment.getExternalStorageDirectory() + savepathname);
Log.e(TAG, "TAKESCREEN 03");
try{
Log.e(TAG, "TAKESCREEN 04");
file.createNewFile();
Log.e(TAG, "TAKESCREEN 05");
FileOutputStream ostream = new FileOutputStream(file);
Log.e(TAG, "TAKESCREEN 06");
bitmap.compress(CompressFormat.PNG, 100, ostream);
Log.e(TAG, "TAKESCREEN 07");
ostream.close();
output = "Successfully saved -> "+savepathname;
}catch (Exception e) {
e.printStackTrace();
output = "Screenshot.java -> "+e;
}
return output;
}
}
If I use findViewbyId, I only get this error: "layoutroot cannot be resolved or is not a field".
While using "getWindow().getDecorView().findViewById(android.R.id.content);" works, but then the app crashes in that part.
Could someone help me with that, please?
Did you implement this part too? If you didn't, place it inside your Screen class. By the way, I strongly believe that going over this activity lifecycle tutorial will help you.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Assuming that button1 and layoutroot are properly described within activity_main.xml

Socket connection test, not working and receive data from hyperterminal

I am creating a socket connection in android eclipse for receiving data first i need to test the connection but the page is not opening on my app, i use a listactivity for my classes.
I want to receive data from my pc(hyperterminal), i have connected a hardware device to my computer which behaves like a router and i want to connect my android phone to the router via Wifi and receive data on my phone as i type on the hyperterminal.
package com.exa.bullseye;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.io.OutputStream;
public class WifiReceive extends Activity {
EditText ip;
EditText s_port;
Button connect;
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(R.layout.wifireceive);
ip = ((EditText)findViewById(R.id.ip));
s_port = ((EditText)findViewById(R.id.port));
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
String address = ip.getText().toString();
InetAddress addr = InetAddress.getByName(address);
int port = Integer.parseInt(s_port.getText().toString());
// Creates a stream socket and connects it to the specified port
// number at the specified IP address. Blocks until the connection succeeds.
Socket socket = new Socket(addr, port);
Toast.makeText(getApplicationContext(), "Socket Connected",
Toast.LENGTH_LONG).show();
socket.close();
}
catch (UnknownHostException e) {
Toast.makeText(getApplicationContext(), "Host not found",
Toast.LENGTH_LONG).show();
}
catch (IOException ioe) {
Toast.makeText(getApplicationContext(), "I/O Exception",
Toast.LENGTH_LONG).show();
}
}
});
}
}

SocketTimeoutException in android-socket Communication

I'm trying to connect my 'Galaxy S' to my Panasonic PLC(or even other PC itself) but I always get an SocketTimeoutException. My android version is 2.3.3:
IP-PLC: 192.168.2.99
IP-GalaxyS: I don't know how to check it
Mask of the network: 255.255.255.0
The PLC is connected directly with the wi-fi router, and I connect my cell phone to this network.
package com.example.communication;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import android.util.Log;
public class TryConnection implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.2.99");
Socket socket = new Socket(serverAddr, 9094);
Log.e("SUCESS", "SUCESS");
} catch(SocketTimeoutException e) {
Log.e("SOCKET TIMEOUT", "SOCKET TIMEOUT", e);
} catch (IOException e) {
Log.e("CONNECTION ", " ERROR", e);
}
}
and my MainActivity Class:
package com.example.communication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendTag(View view) {
TryConnection tryconnection = new TryConnection();
Thread thread = new Thread(tryconnection);
thread.start();
}
}
Do you have any idea for why is it happening ?
It happened with me also, restarted eclipse to resolve the issue.

Connecting android client to C server

I am having trouble connecting my android client to a C server that I wrote. I found another thread with a similar question but unfortunately it was closed saying that it was too narrow. I hope that somebody can answer it here since this is relevant to me as well and all sample codes that I could find online only had the android client connecting to an android server. My client code is the following:
package edu.upenn.seas.cis542;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Try_uiActivity extends Activity
{
//private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "MY IP ADDRESS";
private boolean connected = false;
private Handler handler = new Handler();
final int SERVERPORT = 8080;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//NumberPicker t1 = (NumberPicker)findViewById(R.id.numberPicker3);
//t1.setRange(1, 5);
setContentView(R.layout.main);
}
/*
* When the Submit button is clicked, this method
* gets called.
*/
public void onSubmitClick(View view) {
int item1, item2, item3;
NumberPicker t1 = (NumberPicker)findViewById(R.id.numberPicker1);
item1 = t1.getCurrent();
NumberPicker t2 = (NumberPicker)findViewById(R.id.numberPicker2);
item2 = t2.getCurrent();
NumberPicker t3 = (NumberPicker)findViewById(R.id.numberPicker3);
item3 = t3.getCurrent();
String userInput = "" + item1 + item2 + item3;
//Log.out("Before connecting");
if (!connected) {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Toast toast=Toast.makeText(this, serverAddr.toString(), Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Socket socket = new Socket(serverAddr, SERVERPORT);
connected = true;
} catch (Exception e) {
Toast toast=Toast.makeText(this, "Error2", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
e.printStackTrace();
connected = false;
}
}
}
}
I omitted what I want to do after it is connecting because just creating the socket already gives me an error. My C server opens a connection on the same port that the android program is connecting to. When I tested the server with a java client file, it worked fine. Does anybody know a solution to this? I also added the permissions to the Android Manifest, but that didn't solve the issue. Thanks!

Categories

Resources