Accelerometer Data - Java for Android App Development

I have the code below created but I can not for the life of me figure out how I can send data from the accelerator. I need it to send a constant stream of data until I turn it off. I can't even figure out how to cast the data to a proper variable. Any suggestion would be greatly appreciated.
Code:
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener
{
private static final String TAG = "bluetooth1";
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
Button on, off;
float values;
TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String uuid = tManager.getDeviceId();
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private UUID MY_UUID = UUID
.fromString(uuid);
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "B0:C4:E7:CF:19:6E";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
acceleration = (TextView) findViewById(R.id.accelText);
off = (Button) findViewById(R.id.bOff);
on = (Button) findViewById(R.id.bOn);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
// On click Listeners
off.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
sendData("a");
Toast.makeText(getBaseContext(), "Turn on LED",
Toast.LENGTH_SHORT).show();
}
});
on.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
sendData("a");
Toast.makeText(getBaseContext(), "Turn on LED",
Toast.LENGTH_SHORT).show();
}
});
// End Onclick Listeners
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException
{
if (Build.VERSION.SDK_INT >= 10)
{
try
{
final Method m = device.getClass().getMethod(
"createInsecureRfcommSocketToServiceRecord",
new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e)
{
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@Override
public void onResume()
{
super.onResume();
Log.d(TAG, "...onResume - try 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 = createBluetoothSocket(device);
} catch (IOException e1)
{
errorExit("Fatal Error", "In onResume() and socket create failed: "
+ e1.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...");
try
{
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} 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, "...Create 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");
} else
{
if (btAdapter.isEnabled())
{
Log.d(TAG, "...Bluetooth ON...");
} else
{
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message)
{
Toast.makeText(getBaseContext(), title + " - " + message,
Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message)
{
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try
{
outStream.write(msgBuffer);
} catch (IOException e)
{
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
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 void onAccuracyChanged(Sensor sensor, int accuracy)
{
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event)
{
// TODO Auto-generated method stub
acceleration.setText("x: " + event.values[0] + "\nY:" + event.values[1]
+ "\nZ:" + event.values[2]);
}
}

NoiseAgent said:
I can not for the life of me figure out how I can send data from the accelerator.
Click to expand...
Click to collapse
What's your exact problem? You're getting the data from the accelerator in the onSensorChanged()-Method, so you just need to send them there.

Reply
EmptinessFiller said:
What's your exact problem? You're getting the data from the accelerator in the onSensorChanged()-Method, so you just need to send them there.
Click to expand...
Click to collapse
My problem is I am unsure how to send it. How do you actually do that? I don't know what the syntax is to transmit data over bluetooth. The sendData wont work it gives me the error sendData(String) in the type MainActivity is not applicable for the arguments(Sensor)

Use DataOutputStream and DataInputStream to send/read the three float-values: DataOutputStream#writeFloat(event.values[0/1/2]);

EmptinessFiller said:
Use DataOutputStream and DataInputStream to send/read the three float-values: DataOutputStream#writeFloat(event.values[0/1/2]);
Click to expand...
Click to collapse
Sweet baby jesus, lord all mighty, thank you.

When I add that to the onSensorChanged I get the error "Cannot make a static reference to the non-static method writeFloat(float) from
the type DataOutputStream" not sure how to clear it up.
Also, I have jumped in way over my head, I really just want to wrap this last bit up and start from scratch. If anyone has a good resource for learning object oriented Java programming and would like to share, that would just be the bees-knees.

Of course java/object oriented programming is necessary.
You have to create an object from the ObjectOutputStream like
ObjectOutputStream oos = new ObjectOutputStream(...);
oos.writeFloat(...);
...

Related

Pass Connection Between Intents

I am building an android application to do various queries on my MySQL database. Once a successful login has returned on the main activity, I create a new Intent that holds search and query options. Here's the issue I am having. I keep getting a null pointer exception on stmt = con.createStatement(); Below is my logcat:
Code:
08-20 16:12:07.359 654-810/com.android.exchange D/ExchangeService: !!! deviceId unknown; stopping self and retrying
08-20 16:12:08.469 36-653/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: java.lang.NullPointerException
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at com.example.testapplication.Networking.Search(Networking.java:44)
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at com.example.testapplication.ControlActivity$1.run(ControlActivity.java:53)
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at java.lang.Thread.run(Thread.java:856)
08-20 16:12:12.369 654-654/com.android.exchange D/ExchangeService: !!! EAS ExchangeService, onStartCommand, startingUp = false, running = false
08-20 16:12:12.369 278-498/system_process W/ActivityManager: Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
08-20 16:12:12.369 654-815/com.android.exchange D/ExchangeService: !!! Email application not found; stopping self
08-20 16:12:12.379 278-278/system_process W/ActivityManager: Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
I'm curious whether it is better practice to close the connection and reopen it in the new intent? Or pass the connection between intents somehow?
Any input would be greatly appreciated!
wait...
Here are snippets of my code to help debug.
Code:
[user=439709]@override[/user]
public void onClick(View view) {
if(view.getId() == R.id.LoginButton) {
Toast.makeText(getApplicationContext(), "Attempting Connection", Toast.LENGTH_SHORT).show();
//Spawn new thread
new Thread(new Runnable() {
public void run() {
if(net.execLogin(mUserInput.getText().toString(), mPassInput.getText().toString())) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Connected to Database", Toast.LENGTH_LONG).show();
}
});
//start new activity
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
[user=439709]@override[/user]
public void run() {
Intent intent = new Intent(LoginActivity.this, ControlActivity.class);
startActivity(intent);
}
});
}
else {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Connection Failed :(", Toast.LENGTH_LONG).show();
}
});
}
}
}).start();
}
}
And here is the new activity started by the above code:
Code:
package com.example.testapplication;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class ControlActivity extends Activity implements View.OnClickListener {
private ArrayList<Hardware> list = new ArrayList<Hardware>();
EditText mEditText;
ListView mListView;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control);
setupPage();
}
public void setupPage() {
Button search = (Button)findViewById(R.id.search);
search.setOnClickListener(this);
mEditText = (EditText)findViewById(R.id.editText);
mListView = (ListView)findViewById(R.id.listView);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.control, menu);
return true;
}
public void onClick(View view) {
if(view.getId() == R.id.search) {
new Thread(new Runnable() {
public void run() {
list = new Networking().Search("Type", mEditText.getText().toString());
}
}).start();
ArrayAdapter<Hardware> adapter = new ArrayAdapter<Hardware>(this, android.R.layout.simple_list_item_1, list);
adapter.notifyDataSetChanged();
mListView.setAdapter(adapter);
if(list == null) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "0 Results Yielded :(", Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
And here is the code I use to connect and query the database
Code:
import java.sql.*;
import java.util.*;
public class Networking implements DbQuery {
private static final String DRIVER = "org.mariadb.jdbc.Driver";
private static final String URL = "jdbc:mysql://146.187.16.32/Peirce";
ArrayList<Hardware> ara = new ArrayList<Hardware>();
Database db = new Database();
Hardware h1;
Connection con = null;
Statement stmt = null;
public boolean execLogin(String uName, String pWord) {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, uName, pWord);
if(!con.isClosed()){
return true;
}
return false;
}catch(SQLException e) {
e.printStackTrace();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
public ArrayList<Hardware> Search(String arg, String target) {
try {
stmt = con.createStatement(); //throws null pointer exception
ResultSet rs = stmt.executeQuery("Select * from " + db.getTable() + " where " + arg + "='" + target + "';");
while(rs.next()) {
ara.add(new Hardware(rs.getString("Type"), rs.getString("Make"), rs.getString("Model"), rs.getString("Serial"), rs.getString("Comments")));
}
return ara;
}catch(SQLException e) {
e.printStackTrace();
}catch(NullPointerException e) {
e.printStackTrace();
}
return ara;
}
nevermind
i have figured it out.

url loading handling in webview

Basic question, what did i do? Hahaha. What did i do to make url load inside webview?
At first i overridden shouldOverrideUrlLoading to control where the link loads, then i one time i removed it but url still loads inside webview. And now i need to once again override url loading because i need a link to be opened on the default browser, but i don't know how. I even tried what others suggested to force url loading on the default browser, but it doesn't work. Please help me. Here's my code:
Code:
package com.sample;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
{
private WebView wv;
private ProgressBar progress;
private static String mycaturl="*url 1*";
private static String helpurl="*url 2*";
private static String fbackurl="*url 3*";
[user=1299008]@supp[/user]ressLint("NewApi")
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
if (reachable(this))
{
Toast.makeText(this, "Reachable", Toast.LENGTH_SHORT).show();
buildwv( savedInstanceState, WebSettings.LOAD_DEFAULT, mycaturl );
}
else
{
Toast.makeText(this, "Unreachable", Toast.LENGTH_SHORT).show();
eolc( savedInstanceState );
}
}
[user=1299008]@supp[/user]ressLint({ "SetJavaScriptEnabled" })
public void buildwv(Bundle sis, int load, String url)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
setContentView(R.layout.activity_main);
//assigning objects to variables
wv=(WebView) findViewById(R.id.wv);
wv.setWebViewClient( new wvc() );
progress=(ProgressBar) findViewById(R.id.progress);
//websettings
WebSettings ws = wv.getSettings();
ws.setAppCacheMaxSize( 100 * 1024 * 1024 ); // 100MB
ws.setAppCachePath( this.getCacheDir().getAbsolutePath() );
ws.setAllowFileAccess( true );
ws.setAppCacheEnabled( true );
ws.setJavaScriptEnabled( true );
ws.setCacheMode(load);
//if instance is saved, to catch orientation change
if(sis==null)
{ wv.loadUrl(url); }
}
public void eolc(final Bundle sis)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Unreachable Host");
alertDialog.setMessage("Host is unreachable. Load from cache or exit.");
alertDialog.setIcon(R.drawable.tick);
//alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Load from Cache", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to load cache.", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, mycaturl );
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. EOLC", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
public void roe()
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Connection Lost");
alertDialog.setMessage("Connection to host was lost. Restart and load cache or exit.");
alertDialog.setIcon(R.drawable.tick);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Restart", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
Toast.makeText(getApplicationContext(), "You chose to restart and load cache.", Toast.LENGTH_SHORT).show();
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(i);
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. ROE", Toast.LENGTH_SHORT).show();
wv.stopLoading();
wv.loadUrl( helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
private class wvc extends WebViewClient
{
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
progress.setVisibility(View.VISIBLE);
if (url.contains(mycaturl))
{
WebSettings ws = wv.getSettings();
if ( !reachable(getApplicationContext()) )
{
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
roe();
}
else if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "loading cache coz not reachable", Toast.LENGTH_SHORT).show();
}
}
else
{
if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "Connection to server established.", Toast.LENGTH_SHORT).show();
}
}
}
}
[user=439709]@override[/user]
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
Toast.makeText(getApplicationContext(), "PAGE DONE LOADING!!", Toast.LENGTH_SHORT).show();
//circular progress bar close
progress.setVisibility(View.GONE);
}
[user=439709]@override[/user]
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
super.onReceivedError(view, errorCode, description, failingUrl);
wv.stopLoading();
WebSettings ws = wv.getSettings();
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page unavailable", Toast.LENGTH_SHORT).show();
}
else
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page not cached", Toast.LENGTH_SHORT).show();
}
roe();
}
}
//checking connectivity by checking if site is reachable
public static boolean reachable(Context context)
{
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
try
{
URL url = new URL(mycaturl);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(5000); // five seconds timeout in milliseconds
urlc.connect();
if (urlc.getResponseCode() == 200) // good response
{ return true; } else { return false; }
}
catch (IOException e)
{ return false; }
}
else
{ return false; }
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onBackPressed ()
{
if (wv.isFocused() && wv.canGoBack())
{ wv.goBack(); } else { finish(); }
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.item1:
wv.loadUrl( helpurl );
break;
case R.id.item2:
wv.loadUrl( fbackurl );
break;
case R.id.item3:
String currurl=wv.getUrl();
wv.loadUrl(currurl);
break;
case R.id.item4:
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
break;
case R.id.item5:
finish();
break;
default:
break;
}
return true;
}
[user=439709]@override[/user]
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
wv.saveState(outState);
}
[user=439709]@override[/user]
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
wv.restoreState(savedInstanceState);
}
}
Should i include manifest? Thanks in advance.
That's a messed Op . If your code is short. use code tags. If its big, use paste bin to make it easy for people to read the question and answer it!
vijai2011 said:
That's a messed Op . If your code is short. use code tags. If its big, use paste bin to make it easy for people to read the question and answer it!
Click to expand...
Click to collapse
Sorry, I'm still a newbie. Can you please teach me the proper way of coding android?
klutchmeister said:
Sorry, I'm still a newbie. Can you please teach me the proper way of coding android?
Click to expand...
Click to collapse
He just said that you should wrap your code into
Code:
tags or upload it elsewhere because nobody will read it as it is right now. Can you read that code from your browser? If you put it into [CODE] tags, it will look like this: [URL]http://forum.xda-developers.com/showthread.php?p=44976604#post44976604[/URL]
Then people will be able to read it. ;)
nikwen said:
He just said that you should wrap your code into
Code:
tags or upload it elsewhere because nobody will read it as it is right now. Can you read that code from your browser? If you put it into [CODE] tags, it will look like this: [URL]http://forum.xda-developers.com/showthread.php?p=44976604#post44976604[/URL]
Then people will be able to read it. ;)[/QUOTE]
Oh. sorry. Haha. There, thanks. :)
Click to expand...
Click to collapse

[Q] Sockets in Android

SOLVED. please lock.
I have 2 buttons, Server and Client.
The server button contain a textview which prints stuff received from the client.
The client button open Editbox and Send button which uses OnClick function.
In debug mode everything works fine.
When I run them independently and playing with ON/OFF SocketServer and Existing/New SocketClient the program would mostly get stuck and sometimes i get flowed with "Client says: null"
It usually happens when I click in device1 on Server Button, in device2 on client -> send a message from device2 to device1 and it successes -> close server on device1 -> send about 3 messages on device2 (remember that the serverSocket is closed) -> open server on device1 -> close and open client on device2.
The app also getting stuck randomaly after some turn off screen and turn on using the power button while playing with buttons.. and I cant find the issue.
Server.java:
Code:
package com.example.socketproject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.util.InetAddressUtils;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class Server extends Activity
{
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
private final static int SECONDS_TO_WAIT = 1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
text = (TextView) findViewById(R.id.textview_server);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.server, menu);
return true;
}
@Override
protected void onDestroy()
{
super.onDestroy();
try
{
if (!serverSocket.isClosed())
{
serverSocket.close();
}
if (!serverThread.isInterrupted())
{
serverThread.interrupt();
}
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
}
@Override
protected void onStop()
{
super.onStop();
try
{
if (!serverSocket.isClosed())
{
serverSocket.close();
}
if (!serverThread.isInterrupted())
{
serverThread.interrupt();
}
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
}
private class ServerThread implements Runnable
{
public void run()
{
boolean accepted = false;
InetSocketAddress socketAddr = new InetSocketAddress(59135);
try
{
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(SECONDS_TO_WAIT));
serverSocket.bind(socketAddr);
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
while (!Thread.currentThread().isInterrupted())
{
Socket socket = null;
try
{
socket = serverSocket.accept();
accepted = true;
}
catch (InterruptedIOException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
Thread.currentThread().interrupt();
}
if (accepted)
{
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}
accepted = false;
}
}
}
private class CommunicationThread implements Runnable
{
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
try
{
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
Thread.currentThread().interrupt();
}
}
public void run()
{
while (!Thread.currentThread().isInterrupted())
{
try
{
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
Thread.currentThread().interrupt();
}
}
}
}
private class updateUIThread implements Runnable
{
private String msg;
public updateUIThread(String str)
{
this.msg = str;
}
@Override
public void run()
{
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
Client.java:
Code:
package com.example.socketproject;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.http.conn.util.InetAddressUtils;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class Client extends Activity
{
private final static int SECONDS_TO_WAIT = 5;
private PrintWriter out = null;
private Socket socket = null;
private ClientThread clientThread = new ClientThread();
private String serverIp = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
serverIp = MY_PHONE_IP_HERE;
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.client, menu);
return true;
}
private String getLocalIpAddress()
{
String ipAddr = null;
try
{
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress()) )
{
ipAddr = inetAddress.getHostAddress();
return ipAddr;
}
}
}
}
catch (SocketException ex)
{
Log.d(TAG, ex.toString());
}
return ipAddr;
}
public void onClick(View view)
{
try
{
ExecutorService poolExecutor = Executors.newSingleThreadExecutor();
poolExecutor.execute(clientThread);
poolExecutor.shutdown();
poolExecutor.awaitTermination(SECONDS_TO_WAIT, TimeUnit.SECONDS);
EditText et = (EditText) findViewById(R.id.editText_client);
String str = et.getText().toString();
if(out == null)
{
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
}
out.println(str);
}
catch (UnknownHostException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (Exception e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
}
class ClientThread implements Runnable
{
@Override
public void run()
{
try
{
InetAddress serverAddr = InetAddress.getByName(serverIp);
socket = new Socket();
socket.connect(new InetSocketAddress(serverAddr, 59135), (int) TimeUnit.SECONDS.toMillis(SECONDS_TO_WAIT));
//socket = new Socket(serverAddr, 59135);
}
catch (UnknownHostException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (IOException e)
{
// TODO IF HOST ISNT EXIST
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
}
}
}
EDIT:
nevermind, it was interrupt flag which was erased and made unexpected results with threads. decided to use booleans instead.
Closed at OP's request

[Q] Code placement for writing TCP/IP data to TextView

Hello,
I am a first time poster new to Android app development so please bear with me. I am currently working off of two great TCP/IP Client examples. My goal is to create a simple TCP/IP Client that connects to a server and, once a connection is established, continuously updates a TextView with strings passed from the server. If the user presses a button, the client sends a stop command to the server and I would ultimately like to expand the TextView into a graph with the converted string values. I am able to establish the connection to the server and send the stop command from the client but my attempts at adding the read capability have, so far, been unsuccessful with the app crashing as soon as it starts up.
Since it is my first time posting, I am not allowed to link the examples I am using. If anyone is interested in seeing them, however, they are posts from the android-er blog titled: "Android Server/Client example - client side using Socket" and "Bi-directional communication between Client and Server, using ServerSocket, Socket, DataInputStream and DataOutputStream".
Here is the code in my MainActivity:
Code:
package com.example.androidclient;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textResponse;
TextView textIn;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonStopTest, buttonDisconnect;
Socket socket = null;
DataInputStream incomingString = null;
DataOutputStream terminalLetter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonDisconnect = (Button)findViewById(R.id.disconnect);
buttonStopTest = (Button)findViewById(R.id.stop_test);
textResponse = (TextView)findViewById(R.id.response);
textIn = (TextView)findViewById(R.id.text_in);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonStopTest.setOnClickListener(buttonStopTestOnClickListener);
buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
}
OnClickListener buttonConnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
//Clicking button (Connect) calls a MyClientTask defined below.
MyClientTask myClientTask = new
MyClientTask(editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}
};
OnClickListener buttonStopTestOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
terminalLetter = new DataOutputStream(socket.getOutputStream());
terminalLetter.writeByte('b');
terminalLetter.writeByte('\n');
terminalLetter.close();
socket.close();
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection.");
}
}
};
OnClickListener buttonDisconnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String IPaddress;
int Port;
String response = "";
MyClientTask(String addr, int port){
IPaddress = addr;
Port = port;
}
@Override
protected Void doInBackground(Void... arg0) {
//Took socket declaration from here.
try {
//Taking relevant parameters and applying them to socket
socket = new Socket(IPaddress, Port);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
incomingString = new DataInputStream(socket.getInputStream());
textIn.setText(incomingString.readUTF());
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
finally{
if(socket != null){
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
I put the commands for reading data from the server and writing it to the TextView with the code that sets up the connection to the socket. The idea was that it would be the next step after the connection is established but I realize that it looks like I am only reading once. I tried adding a while loop and bringing it out of the doInBackground. In each case, all I got was the whole app crashing on me. It looks fairly straight forward in the example but there the connection is automatic, not triggered and I have not been able to modify the code successfully.
I am still new to Android and this feels like it is an important part of app development so I am hoping someone in the community can help me understand where the section of code relevant to reading data (continuously) should be placed in relation to the rest.
Best,
Yusif Nurizade
P.S. I was going to include the fragment but, since the post is long enough, I chose to omit it. I can share upon request and the logcat.

[Q] Create notification when bluetooth data is received in the background

I am currently working on an arduino project that connects to my phone using a bluetooth module.
On the arduino I have various diagnostic sensors hooked up to it. When the sensors "sense an error," I would like to receive a notification on my phone.
I'm guessing this would require me to program an app that runs as a background service listening for data coming across the bluetooth connection. Then when it receives the data it would need to create a notification and play the system notification sound.
Is it even possible to listen to the data coming from the bluetooth module while being run in the background?
How hard would this be for me, a beginner, to program? I have programmed in several other languages (html, visual basic, and python), so I understand basic coding concepts.
I would like to thank everyone for all the help. The amount of replies just shows how useful this forum is to beginning devs.
Anyways, after three days of straight research, I pumped out a working app. Now I would like for someone to review my code and see if anything can be revised or done better, as I really don't know what I'm doing.
The main activity:
Code:
package com.example.bluetooth;
//Import needed files
import java.util.ArrayList;
import java.util.Set;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
//Main activity class
public class MainActivity extends ActionBarActivity {
//Creates object variables
private Button list, disconnect;
private ListView lv;
private BluetoothAdapter BA;
private Set<BluetoothDevice> pairedDevices;
private Toast toast;
@Override
//on create
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creates variables containing id's
list = (Button) findViewById(R.id.button1);
disconnect = (Button) findViewById(R.id.button2);
lv = (ListView) findViewById(R.id.listView1);
//When you click the list item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object obj = lv.getAdapter().getItem(position);
String str = obj.toString();
int strStartIndex = str.indexOf("\n");
str = str.substring(strStartIndex + 1);
//check to see if bluetooth is enabled before
//starting the service
if (BA.isEnabled()) {
toast = Toast.makeText(getApplicationContext(),
"Connecting to: " + str, Toast.LENGTH_SHORT);
toast.show();
//connects to item you tapped, creating a service
Intent btConnectIntent = new Intent(MainActivity.this, ForegroundService.class);
btConnectIntent.setAction("btConnect");
btConnectIntent.putExtra("mac", str);
startService(btConnectIntent);
}
//Bluetooth isn't enabled
else{
toast = Toast.makeText(getApplicationContext(),
"Bluetooth must be enabled!", Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
//When you click the list button
public void list(View view) {
//Get bluetooth adapter and set it to BA
BA = BluetoothAdapter.getDefaultAdapter();
//Make sure device has bluetooth
if (BA != null) {
//See if bluetooth is enabled and if it is, get the list of paired devices
if (BA.isEnabled()) {
bluetoothList();
}
//If bluetooth isn't enabled, enable it
else {
//Start new intent to see if they turn on bluetooth
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
toast = Toast.makeText(getApplicationContext(),
"Bluetooth must be on!", Toast.LENGTH_SHORT);
toast.show();
}
}
//Device doesn't have a bluetooth adapter
else {
toast = Toast.makeText(getApplicationContext(),
"Your device doesn't support bluetooth!", Toast.LENGTH_SHORT);
toast.show();
}
}
//Waiting to see if they turn on bluetooth
//If they do, show list
public void onActivityResult(int requestCode, int resultCode, Intent turnOn) {
//if it turned on successfully, get the list of paired bluetooth devices
if (resultCode == RESULT_OK) {
bluetoothList();
}
}
//When they click disconnect button, stop the service
public void disconnect(View view) {
Intent stopIntent = new Intent(MainActivity.this, ForegroundService.class);
stopIntent.setAction("stopForeground");
startService(stopIntent);
}
//Method that gets the list of paired devices
private void bluetoothList() {
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for (BluetoothDevice bt : pairedDevices)
list.add(bt.getName() + "\n" + bt.getAddress());
//create array adapter
final ArrayAdapter adapter = new ArrayAdapter
(this, android.R.layout.simple_list_item_1, list);
//connect our list view to the adapter
lv.setAdapter(adapter);
toast = Toast.makeText(getApplicationContext(),
"Showing paired devices", Toast.LENGTH_SHORT);
toast.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
And the foreground service:
Code:
package com.example.bluetooth;
//Import needed files
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
//Service class
public class ForegroundService extends Service {
int FOREGROUND_ID = 1997;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter BA;
private BluetoothSocket BS;
private StringBuilder sb = new StringBuilder();
private Toast toast;
private String mac;
private Handler h;
//When the service is created
//Doesn't run again unless service is totally killed
public void onCreate() {
//Set service as foreground service
startForeground(FOREGROUND_ID, buildForegroundNotification());
toast = Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_SHORT);
toast.show();
//Get bluetooth adapter and set it to BA
BA = BluetoothAdapter.getDefaultAdapter();
//Create a handler to listen for data
//New threads send data to this handler
//If it receives data, show it in a toast
h = new Handler() {
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
toast = Toast.makeText(getApplicationContext(), bundle.getString("str"), Toast.LENGTH_SHORT);
toast.show();
}
;
};
}
//Called every time an activity runs startService
public int onStartCommand(Intent intent, int flags, int startId) {
//When an activity starts the service, it sends an action
//Check if action = btConnect
if (intent.getAction().equals("btConnect")) {
//Make sure there's not already an open socket
if (BS == null) {
//Creates a bundle to get data
Bundle extras = intent.getExtras();
//Extracts data from bundle, in this case the mac address
mac = extras.getString("mac");
//Creates another handler to listen for data
final Handler mHandler = new Handler();
//A runnable called when can't connect
final Runnable hUnsuccessful = new Runnable() {
public void run() {
toast = Toast.makeText(getApplicationContext(),
"Unsuccessful", Toast.LENGTH_SHORT);
toast.show();
toast = Toast.makeText(getApplicationContext(), "Service stopped", Toast.LENGTH_SHORT);
toast.show();
//Kill the service
stopForeground(true);
stopSelf();
}
};
//A runnable called when successfully connected
final Runnable hSuccessful = new Runnable() {
public void run() {
//Run method using socket BS
//Method listens for data coming across socket
ConnectedThread(BS);
toast = Toast.makeText(getApplicationContext(),
"Successful", Toast.LENGTH_SHORT);
toast.show();
}
};
//Creates a new thread since BS.connect
//will block the main thread otherwise
Thread thread = new Thread() {
public void run() {
//Creates BluetoothDevice from the mac address
//mac address was passed to service in onStartCommand
BluetoothDevice device = BA.getRemoteDevice(mac);
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
BS = device.createRfcommSocketToServiceRecord(MY_UUID);
}
//If it can't create a socket
catch (IOException e) {
//Send unsuccessful to the handler
mHandler.post(hUnsuccessful);
return;
}
// Cancel discovery because it will slow down the connection
BA.cancelDiscovery();
//Try to connect
try {
BS.connect();
}
// Unable to connect, send a toast and close the socket
catch (IOException connectException) {
//Try to close socket
try {
if (BS != null) {
BS.close();
BS = null;
}
//Send unsuccessful to the handler
mHandler.post(hUnsuccessful);
return;
}
//Can't close socket, do nothing
catch (IOException closeException) {
}
}
//If it made it to here, it was successful
//Send successful to the handler
mHandler.post(hSuccessful);
}
};
//Start the thread
thread.start();
}
//if BS != null
//Currently connected to a socket
else {
toast = Toast.makeText(getApplicationContext(), "You must disconnect first", Toast.LENGTH_SHORT);
toast.show();
}
}
//When an activity starts the service, it sends an action
//Check if action = stopForeground
if (intent.getAction().equals("stopForeground")) {
toast = Toast.makeText(getApplicationContext(), "Service stopped", Toast.LENGTH_SHORT);
toast.show();
//Try to close socket if one is open
try {
if (BS != null) {
BS.close();
BS = null;
toast = Toast.makeText(getApplicationContext(),
"Bluetooth device disconnected", Toast.LENGTH_SHORT);
toast.show();
}
}
//If it can't close it, do nothing
catch (IOException e) {
}
//Kill the service
stopForeground(true);
stopSelf();
}
//Service should stay alive, unless we kill it
return START_STICKY;
}
//Method to create foreground notification
private Notification buildForegroundNotification() {
NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
notification.setOngoing(true);
notification.setContentTitle("Bluetooth Service")
.setContentText("Service to listen for bluetooth data")
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setPriority(Notification.PRIORITY_MIN);
return (notification.build());
}
//Method to create a notification
private void notification(String title, String text) {
int mId = 0;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setContentTitle(title)
.setContentText(text)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setPriority(NotificationCompat.PRIORITY_MAX);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
}
//Looping method to listen for data over bluetooth socket
private void ConnectedThread(BluetoothSocket socket) {
final InputStream mmInStream;
InputStream tmpIn = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
//Create new thread as it will otherwise block main thread
Thread thread = new Thread() {
public void run() {
byte[] buffer = new byte[256]; //buffer store for the stream
int bytes; //bytes returned from read()
//Keep listening to the InputStream until an exception occurs
while (true) {
try {
Message msg = new Message();
Bundle bundle = new Bundle();
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
String strIncom = new String(buffer, 0, bytes);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\r\n");
if (endOfLineIndex > 0) {
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
bundle.putString("str", sbprint);
msg.setData(bundle);
h.sendMessage(msg);
notification("Sensor Data:", sbprint);
}
}
//If InputStream gets interrupted
catch (IOException e) {
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("str", "Lost connection");
msg.setData(bundle);
h.sendMessage(msg);
notification("Error", "Lost connection");
Intent stopIntent = new Intent(getApplicationContext(), ForegroundService.class);
stopIntent.setAction("stopForeground");
startService(stopIntent);
break;
}
}
}
};
//Start the thread
thread.start();
}
//Required
public IBinder onBind(Intent intent) {
return null;
}
}

Categories

Resources