I have my major project on android based home automation system meaning that I have to control home appliances using android bluetooth. I am using HC-05 bluetooth module which receives the string sent to it through my application, sends it to PIC16f877a and the pic in turn depending upon the string received, controls the appliances. Now my problem is that I have been able to pair and connect the devices through my application but my application is not sending the characters which I want to send when I click the button. Note that PIC and the Bluetooth module are working fine. please help me. I am posting my code below hope you guys won't mind.
package com.chainedcat.splashscreen;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.UUID;
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.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivityActivity extends Activity{
private BluetoothAdapter BA;
private ArrayList<BluetoothDevice> devices;
private ListView lv;
private TextView text;
private BluetoothSocket btSocket=null;
private ArrayAdapter<String> btArrayAdapter;
private static final int REQUEST_ENABLE_BT = 1;
private UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34EB");
private OutputStream outStream=null;
public void Init(){
BA = BluetoothAdapter.getDefaultAdapter();
text =(TextView) findViewById(R.id.text);
lv = (ListView) findViewById(R.id.listView1);
devices = new ArrayList<BluetoothDevice>();
btArrayAdapter= new ArrayAdapter<String>this,android.R.layout.simple_list_item_1);
lv.setAdapter(btArrayAdapter);
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Init();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
BluetoothDevice selectedDevice = devices.get(arg2);
if(selectedDevice.getBondState()== BluetoothDevice.BOND_NONE){
pairDevice(selectedDevice);
}
else if(selectedDevice.getBondState()==BluetoothDevice.BOND_BONDED){
connect(selectedDevice);
}
}
});
}
public void bluetooth(View view){
if(!BA.isEnabled()){
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(btIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Bluetooth turned on!!", Toast.LENGTH_LONG).show();
btExtra();
}else{
Toast.makeText(getApplicationContext(), "Bluetooth is already on!!", Toast.LENGTH_LONG).show();
btExtra();
}
}
public void btExtra(){
btArrayAdapter.clear();
BA.startDiscovery();
registerReceiver(btReceiver, new tentFilter(BluetoothDevice.ACTION_FOUND));
}
final BroadcastReceiver btReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String status=null;
if(device.getBondState()==BluetoothDevice.BOND_BONDED){
status="paired";
}else{status="not paired";}
btArrayAdapter.add(device.getName()+" : "+status+"\n"+device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}
};
#Override
protected void onActivityResult(int requestCode,int resultCode, Intent data){
if(requestCode==REQUEST_ENABLE_BT){
if(BA.isEnabled()){
text.setText("Bluetooth Status:Enabled");
}else{
text.setText("Bluetooth Status:Disabled");
}
}
}
private void pairDevice(BluetoothDevice device) {
Method m=null;
try {
m = device.getClass().getMethod("createBond", (Class[]) null);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
m.invoke(device, (Object[]) null);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connect(device);
}
public void connect(BluetoothDevice device){
Toast.makeText(getApplicationContext(), "connecting....", Toast.LENGTH_LONG).show();
try {
btSocket=device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BA.cancelDiscovery();
try {
Toast.makeText(getApplicationContext(), "entered in run", Toast.LENGTH_LONG).show();
btSocket.connect();
if(btSocket!=null){btSocket.close();}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void send(String s){
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bytes = s.getBytes();
try {
outStream.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fan(View v){
send("f");
}
#Override
public void onDestroy(){
super.onDestroy();
BA.disable();
unregisterReceiver(btReceiver);
}
}
Related
Im almost getting to the end of my Sound bar project (2 arduinos, relays, digital potentiometers, leds, i2c, bluetooth and ir remote, diy amplifier,...) and I`m stuck.
This is my first time using android studio and things are becoming so hard for me.
I created an app with a few buttons, switch, sliders and dropdown menu that connects to bluetooth module and sends values to my arduino.
Now I need to add a script that would receive values that arduino is sending (got arduino code done), and would eventualy set buttons clickable/unclickable and set slider positions depending on values being received thru bluetooth.
Can somebody please show me the way to read values from bluetooth and store them in integer or something so that buttons could be disabled and enabled with if(integer=x); statements.
I will post my java code (App is almost done, excepet for sliders and this bluetooth receive part) and I will post the code I came with so far...
I`m going nuts on this one.
Thank you for help :)
package com.interface80.soundbarcontrol;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ActivityInfo;
import android.icu.text.Transliterator;
import android.os.Build;
import android.os.*;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;
public class Remote extends Activity implements AdapterView.OnItemSelectedListener {
private static final String TAG = "BlueTest5-Controlling";
private int mMaxChars = 50000;//Default//change this to string..........
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
private boolean mIsUserInitiatedDisconnect = false;
private boolean mIsBluetoothConnected = false;
private int mLastSpinnerPosition = 0;
private Button mBtnDisconnect;
private BluetoothDevice mDevice;
final static String on="92";//on
final static String off="79";//off
final static String subon="10";//subon
final static String suboff="15";//suboff
final static String zero="20";//zeroDB
final static String six="25";//sixDB
final static String twelwe="30";//twelweDB
final static String userBoost="40";
final static String softBoost="45";
final static String normalBoost="50";
final static String hardBoost="55";
final static String overloadOn="60";
final static String overloadOff="65";
Switch toggle; //outside oncreate
private ProgressDialog progressDialog;
Button btnon,btnoff, btnsubon, btnsuboff, btnzero, btnsix, btntwelwe;
Switch overloadSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remote);
Spinner spinnerPresets = (Spinner) findViewById(R.id.spinnerPresets);
ArrayAdapter<String> adapterPresets = new ArrayAdapter<String>(Remote.this,
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.arrayPresets));
adapterPresets.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPresets.setAdapter(adapterPresets);
spinnerPresets.setOnItemSelectedListener(this);
ActivityHelper.initialize(this);
// mBtnDisconnect = (Button) findViewById(R.id.btnDisconnect);
btnon = (Button) findViewById(R.id.on);
btnoff = (Button) findViewById(R.id.off);
btnsubon = (Button) findViewById(R.id.subon);
btnsuboff = (Button) findViewById(R.id.suboff);
btnzero = (Button) findViewById(R.id.zero);
btnsix = (Button) findViewById(R.id.six);
btntwelwe = (Button) findViewById(R.id.twelwe);
overloadSwitch = (Switch) findViewById(R.id.overloadSwitch);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
btnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(on.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(off.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsubon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(subon.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsuboff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(suboff.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnzero.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(zero.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsix.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(six.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btntwelwe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(twelwe.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
if (mLastSpinnerPosition == position)
{
return;
}
mLastSpinnerPosition = position;
if (0 == position) {
Toast.makeText(parent.getContext(), "Boost controlled by user.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(true);
btnsix.setEnabled(true);
btntwelwe.setEnabled(true);
try {
mBTSocket.getOutputStream().write(userBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
if (1 == position) {
try {
mBTSocket.getOutputStream().write(softBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
if (2 == position) {
try {
mBTSocket.getOutputStream().write(normalBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
if (3 == position) {
try {
mBTSocket.getOutputStream().write(hardBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private class ReadInput implements Runnable {
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i = 0;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {//cant inderstand these dotss
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Remote.this, "", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device`
// e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect.Please turn on Sound bar", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to Sound bar");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
public void toggle( View View) //outside oncreate
{
if( overloadSwitch.isChecked() ){
try {
mBTSocket.getOutputStream().write(overloadOn.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
else
{
try {
mBTSocket.getOutputStream().write(overloadOff.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
}
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
byte[] buffer = new byte[1024];
inputStream.read(buffer);
int BTvalue = buffer;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Problem solved.
I spent late night yesterday with no succes. Angry and frustrated I went to bed. Today I found out that none of the codes I was trying didn`t work, because code was already there. Reading and writing to string. Just used the string and done :)
I am implementing the bound service for the socket.io implementation in android for single socket maintenance to connect with nodejs server by this Gottox library. When I implementing this the memory of the service is not stable like while on starting of the service it takes around 30MB to 40MB, after some time it also leads to 200MB. So I thought it may be memory leak. But i don't get any single clue to find it.
Codes
DemoActivity.java
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.actionbarsherlock.app.SherlockActivity;
import com.devspark.appmsg.AppMsg;
import com.devspark.appmsg.AppMsg.Style;
import com.nuappz.Demo.DemoService.MyLocalBinder;
import com.nuappz.Demo.handler.ResponseHandler;
import com.nuappz.Demo.helper.MySharedPreferences;
public class DemoActivity extends SherlockActivity {
MySharedPreferences pref;
DemoService socketService;
boolean isBound;
EditText name, mobile_no, email, password;
Button Demo;
Style style_alert, style_success;
JSONObject json_Demo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Demo);
isBound = false;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// start the bind service
if (!isBound) {
bindService(new Intent(DemoActivity.this,
DemoService.class), myConnection,
Context.BIND_AUTO_CREATE);
isBound = true;
startService(new Intent(this, DemoService.class));
socketService = DemoService.getInstance();
}
}
public ServiceConnection myConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
isBound = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
socketService = ((MyLocalBinder) service).getService();
isBound = true;
}
};
protected void onDestroy() {
if (isBound) {
// Disconnect from an application service. You will no longer
// receive calls as the service is restarted, and the service is
// now allowed to stop at any time.
unbindService(myConnection);
isBound = false;
}
stopService(new Intent(DemoActivity.this, DemoService.class));
super.onDestroy();
}
}
DemoService.java
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;
import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.nuappz.Demo.handler.ResponseHandler;
import com.nuappz.Demo.helper.MySharedPreferences;
/*
* This class is Background service for the Blood Drop application
*/
public class DemoService extends Service {
private static final String serverUrl = "http://nuappzdev.hello.com:8080/";
private static SocketIO socket;
private static DemoService instance;
private static ResponseHandler handler;
public boolean bound;
JSONObject jobj_in = new JSONObject();
#Override
public void onCreate() {
// TODO Auto-generated method stub
Log.d("Service", "Started");
super.onCreate();
// connecting socket
try {
DemoService.initInstance();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public DemoService() {
}
public static DemoService getInstance() {
return instance;
}
// start the service to handle the functions
public int onStartCommand(Intent intent, int flags, int startId) {
// HandleReceiveRequest();
return START_STICKY;
}
// Stop the services
public void onDestroy() {
Log.d("Service", "Stopped");
getSocket().disconnect();
}
// Binder class initialize
public class MyLocalBinder extends Binder {
DemoService getService() {
return DemoService.this;
}
}
private final IBinder myBinder = new MyLocalBinder();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
bound = true;
return myBinder;
}
// initiate the socket connection
public static void initInstance() throws MalformedURLException {
if (instance == null) {
instance = new DemoService();
if (DemoService.getSocket() == null) {
DemoService.setSocket(new SocketIO());
}
DemoService.connectIO();
}
}
// Method to get socket
public static SocketIO getSocket() {
return socket;
}
// Method to set socket
public static void setSocket(SocketIO socket) {
DemoService.socket = socket;
}
// Method to ConnectIO to server
public static void connectIO() throws MalformedURLException {
try {
SocketIO.setDefaultSSLSocketFactory(SSLContext.getDefault());
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DemoService.getSocket().connect(serverUrl, new IOCallback() {
#Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(String data, IOAcknowledge ack) {
}
#Override
public void onError(SocketIOException socketIOException) {
Log.d("Connection:", "Error in Connection");
}
#Override
public void onDisconnect() {
// TODO Auto-generated method stub
Log.d("Connection:", "disConnected");
}
#Override
public void onConnect() {
Log.d("Connection:", "Connected");
}
#Override
// Method to getting response from server
public void on(String event, IOAcknowledge ack, Object... args) {
JSONArray jarr_args = new JSONArray();
JSONObject jobj_in = new JSONObject();
try {
jarr_args.put(args[0]);
jobj_in = jarr_args.getJSONObject(0);
jobj_in.put("event", event);
Log.d("jobject: event", jobj_in.getString("event"));
try {
handler.handleObject(jobj_in);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
// Method to send request to server
public static void emit(String event, Object args,
ResponseHandler responseHandler) throws MalformedURLException {
handler = responseHandler;
if (DemoService.getSocket().isConnected() == false) {
DemoService.getSocket().reconnect();
}
DemoService.getSocket().emit(event, args);
}
// Method to send request to server with Acknowledge
public static void emitWithAcknowledge(String event, Object args)
throws MalformedURLException {
if (DemoService.getSocket().isConnected() == false) {
DemoService.getSocket().reconnect();
}
DemoService.getSocket().emit(event, new IOAcknowledge() {
#Override
public void ack(Object... args) {
// TODO Auto-generated method stub
}
}, args);
}
}
}
What are the chances of memory leak in this code.
You needs to unbind service in onStop of your activity and you should never call stopService from your activity. Let Android do the handling of life cycle of your service.
When I am trying to call a number from listview, the dialer opens but shows me some different. The listview consists of two image button, one button is used to make call.
This is my Custom Adapater Class EmergencyNumCustomAdapaterForCall.java.
package com.example.panicapp;
import java.util.List;
import com.example.panicapp.AppDao.AddEmerNumAuthenticationDao;
import com.example.panicapp.AppModel.AddEmergencyNumber;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.ListAdapter;
public class EmergencyNumCustomAdapaterForCall extends ArrayAdapter<AddEmergencyNumber> implements ListAdapter{
private List<AddEmergencyNumber> lsadd;
private LayoutInflater inflator;
private AddEmerNumAuthenticationDao emerdao=null;
public EmergencyNumCustomAdapaterForCall(AddEmergencyNumberForCall addnum, List<AddEmergencyNumber> ls)
{
super(addnum, R.layout.activity_custom_numberlisting, ls);
// TODO Auto-generated constructor stub
this.lsadd=ls;
inflator=addnum.getLayoutInflater();
}
static class ViewHolder
{
protected TextView emernumber;
protected ImageButton imgbtncall;
protected ImageButton imgbtnDelete;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ViewHolder viewholder=null;
final int temposition=arg0;
if(arg1==null)
{
arg1=inflator.inflate(R.layout.activity_custom_numberlisting, null);
viewholder=new ViewHolder();
viewholder.emernumber=(TextView)arg1.findViewById(R.id.txt_numberlisting);
viewholder.imgbtncall=(ImageButton)arg1.findViewById(R.id.img_numberlisting);
viewholder.imgbtnDelete=(ImageButton)arg1.findViewById(R.id.img_numdelete);
viewholder.imgbtnDelete.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
emerdao=new AddEmerNumAuthenticationDao(getContext());
emerdao.deleteCallNum(lsadd.get(temposition).getEmergencyNumber());
Log.i("Authentication", "Number Deleted");
}
});
viewholder.imgbtncall.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
emerdao=new AddEmerNumAuthenticationDao(getContext());
emerdao.getEmergencyNumberForCalling(lsadd.get(temposition).getEmergencyNumber());
String number=""+emerdao;
System.out.println(number);
Log.i("Number", "Calling Number");
Intent callintent=new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" +emerdao));
getContext().startActivity(callintent);
}
});
arg1.setTag(viewholder);
arg1.setTag(R.id.txt_numberlisting, viewholder.emernumber);
arg1.setTag(R.id.img_numberlisting, viewholder.imgbtncall);
arg1.setTag(R.id.img_numdelete, viewholder.imgbtnDelete);
}
else
{
viewholder=(ViewHolder)arg1.getTag();
}
viewholder.imgbtncall.setTag(arg0);
viewholder.imgbtnDelete.setTag(arg0);
viewholder.emernumber.setText(lsadd.get(arg0).getEmergencyNumber());
return arg1;
}
}
This is my database class
package com.example.panicapp.AppDao;
import java.util.ArrayList;
import java.util.List;
import com.example.panicapp.AppModel.AddEmergencyNumber;
import com.example.panicapp.AppUtill.DbUtill;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class AddEmerNumAuthenticationDao extends SQLiteOpenHelper implements AddEmerNumAuthenticationListener{
private SQLiteDatabase sqlDb=null;
public AddEmerNumAuthenticationDao(Context context) {
super(context, DbUtill.DATABASE_NAME, null, DbUtill.DATABASE_VERSION);
Log.i("AuthenticationDao", "This is AuthenticationDao constructor.....");
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
#Override
public List<AddEmergencyNumber> getAllEmergencyNumberforcall()
{
// TODO Auto-generated method stub
List<AddEmergencyNumber> addemergnum=new ArrayList<AddEmergencyNumber>();
sqlDb=this.getReadableDatabase();
Cursor cursor=null;
cursor=sqlDb.query(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, new String[] {DbUtill.EMERGENCYNUMBER,DbUtill.CALL}, DbUtill.CALL+"=?", new String[] {"1"}, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
AddEmergencyNumber addnum=new AddEmergencyNumber();
addnum.setEmergencyNumber(cursor.getString(0));
addnum.setCall(cursor.getInt(1));
addemergnum.add(addnum);
cursor.moveToNext();
}
cursor.close();
sqlDb.close();
return addemergnum;
}
#Override
public List<AddEmergencyNumber> getAllEmergencyNumberforsms() {
// TODO Auto-generated method stub
List<AddEmergencyNumber> addemergnum=new ArrayList<AddEmergencyNumber>();
sqlDb=this.getReadableDatabase();
Cursor cursor=null;
cursor=sqlDb.query(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, new String[] {DbUtill.EMERGENCYNUMBER,DbUtill.SMS}, DbUtill.SMS+"=?", new String[] {"1"}, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
AddEmergencyNumber addnum=new AddEmergencyNumber();
addnum.setEmergencyNumber(cursor.getString(0));
addnum.setSms(cursor.getInt(1));
addemergnum.add(addnum);
cursor.moveToNext();
}
cursor.close();
sqlDb.close();
return addemergnum;
}
#Override
public List<AddEmergencyNumber> getAllNumberforGps() {
// TODO Auto-generated method stub
List<AddEmergencyNumber> addemergnum=new ArrayList<AddEmergencyNumber>();
sqlDb=this.getReadableDatabase();
Cursor cursor=null;
cursor=sqlDb.query(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, new String[] {DbUtill.EMERGENCYNUMBER,DbUtill.GPS}, DbUtill.GPS+"=?", new String[] {"1"}, null, null, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
AddEmergencyNumber addnum=new AddEmergencyNumber();
addnum.setEmergencyNumber(cursor.getString(0));
addnum.setGps(cursor.getInt(1));
addemergnum.add(addnum);
cursor.moveToNext();
}
cursor.close();
sqlDb.close();
return addemergnum;
}
#Override
public void deleteAllCallNum()
{
// TODO Auto-generated method stub
try
{
sqlDb=this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.CALL+"=?",new String[] {"1"});
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
#Override
public void deleteAllSmsNum()
{
// TODO Auto-generated method stub
try
{
sqlDb=this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.SMS+"=?",new String[] {"1"});
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
#Override
public void deleteAllGpsNum() {
// TODO Auto-generated method stub
try
{
sqlDb=this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.GPS+"=?",new String[] {"1"});
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
public void deleteCallNum(String i)
{
// TODO Auto-generated method stub
try
{
sqlDb = this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.EMERGENCYNUMBER+"=?",new String[] {String.valueOf(i)});
Log.i("DELETECALLNUMBER", "DeletionNumber");
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
public void deleteSmsNum(String id)
{
// TODO Auto-generated method stub
try
{
sqlDb = this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.EMERGENCYNUMBER+"=?",new String[] {String.valueOf(id)});
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
#Override
public void deleteGpsNum(String id) {
// TODO Auto-generated method stub
try
{
sqlDb = this.getWritableDatabase();
sqlDb.delete(DbUtill.TABLE_ADD_EMERGENCY_NUMBER, DbUtill.EMERGENCYNUMBER+"=?",new String[] {String.valueOf(id)});
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
public void getEmergencyNumberForCalling(String id) {
// TODO Auto-generated method stub
try
{
sqlDb=this.getWritableDatabase();
String query="SELECT "+DbUtill.EMERGENCYNUMBER+" FROM "+DbUtill.TABLE_ADD_EMERGENCY_NUMBER+" WHERE "+DbUtill.CALL+ "=?"+" ";
sqlDb.rawQuery(query, null);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(sqlDb.isOpen())
{
sqlDb.close();
}
}
}
}
Im trying to make an app witch looks on a JSON encoded php file, there that all right. All runs perfectly, but now im attempting to put that class into a Service beacuse i want to run it on background and repeatedly, but application crushes, (on the phone and simulated)
So can anyone tell me whats wrong here?
Here is the code
First the main activity . java
[...]IMPORTS
public class ServiceMainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
}
public void onClickComenzar(View v) {
startService(new Intent(getBaseContext(), MyService.class));
}
public void onClickDetener(View v) {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
And here the Service activity . java , the place where im trying to put my asynctask
package attempt.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.text.Html;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
try {
new DoBackgroundTask().execute("http://iatek.eu/sys/getsmsx.php");
} catch (Exception ex) {
ex.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getBaseContext(), "service stoped",
Toast.LENGTH_SHORT).show();
}
private class DoBackgroundTask extends AsyncTask<String, String, JSONObject> {
#Override
protected JSONObject doInBackground(String... urls) {
JSONObject obj = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
// HttpResponse response = httpclient.execute(httppost);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
obj = new JSONObject(jsonResult);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return obj;
}
protected void onProgressUpdate( ) {
// TODO Auto-generated method stub
}
#Override
protected void onPostExecute(JSONObject obj) {
JSONArray jsonArray;
String dana = null;
try {
jsonArray = obj.getJSONArray("posts");
JSONObject childJSONObject = jsonArray.getJSONObject(1);
String sms = childJSONObject.getString("sms");
Toast.makeText(getBaseContext(), "sms"+sms,
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}
public StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
}
My objetive on this code is to show some php data on a toast, but it doesnt... i dont know why, help me pleasee!!
Thanks a lot!
I think using InentService is better suited for what you are trying to accomplish. It runs on a separate Thread, and it stops itself when it is done.
I'm very inexperienced with both Java and Android development. But I managed to make a simple Android application to read the proximity sensor value. I also managed to write a Java application that edited a cell in a google spread sheet.
So now I want to combine the two and have the Android app that will change the value of a cell in a google spreadsheet based on the value of the poximity sensor.
However, when I combine the code, my app crashes and I don't know enough about the Eclipse environment and debuggers to figure out what's going on. The app installs fine and lunches. The main view shows up for just a second then the app crashes.
package com.example.mysensorproject;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.CellEntry;
import com.google.gdata.data.spreadsheet.CellFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
public class MainActivity extends Activity implements SensorEventListener {
TextView proxText;
SensorManager sm;
Sensor proxSensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
proxSensor=sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
proxText=(TextView)findViewById(R.id.proximityTextView);
sm.registerListener(this, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
#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) {
proxText.setText(String.valueOf(event.values[0]));
//change value in spreadsheet
SpreadsheetService service = new SpreadsheetService("wise");
service.setProtocolVersion(SpreadsheetService.Versions.V3);
try {
service.setUserCredentials("email#example.com", "password");
} catch (AuthenticationException e) {
e.printStackTrace();
}
URL url = null;
try {
url = new URL("https://spreadsheets.google.com/feeds/cells/0AuDoKcCfLURKdEQ3bVFLemY5aVh2SGQySE10QTYzRGc/od6/private/full");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CellFeed cellFeed = null;
try {
cellFeed = service.getFeed(url, CellFeed.class);
// System.out.println("Cell Feed Worked");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (CellEntry cell : cellFeed.getEntries()) {
cell.changeInputValueLocal(String.valueOf(event.values[0]));
try {
cell.update();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
}
}
This occurs when u trying to do in the UI. You need to do in background (Thread). You can use something like AsyncTask: (http://developer.android.com/reference/android/os/AsyncTask.html).
Some code For example:
public class TaskModifySpreadsheet extends AsyncTask <Spreadsheet, Object, Spreadsheet>
{
#Override
protected Spreadsheet doInBackground(Spreadsheet... titles) {
// Do all work with the spreadsheet here. Modify cells, retrieving... etc.
}
}