cannot print the value taken from socket connection - java

public class MyClientTask extends AsyncTask<String, String, String> {
String dstAddress;
int dstPort;
MyClientTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
protected String doInBackground(String... arg0) {
String response = "";
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((response = stdIn.readLine()) != null) {
Log.i("response", response);
publishProgress(response);
}
Log.i("response", response);
} catch (UnknownHostException e) {
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
response = "IOException: " + e.toString();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onProgressUpdate(String... values) {
Log.i("prama", values[0]);
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
I write above code to read value from socket.when i start the async task the value will be print on the log as i do in doInbackground but my toast message will not be fired after the async task finished.

Related

Android Sockets not working in reality

I am trying to connect an Android device to a java server. It works perfectly when I use the emulator but when I port it onto my phone there is no connection.
The aim of the code is to send a value from client to server, perform a calculation on it and return it back to the client to be displayed.
This is my server code:
public class ServerTest {
public static final int PORT_NUMBER = 8000;
protected Socket socket;
private ServerTest(Socket socket) {
this.socket = socket;
System.out.println("New client connected from " + socket.getInetAddress().getHostAddress());
connect();
}
public void connect() {
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String request = br.readLine();
if (request.equals("end")) {
System.out.println("Message received: " + request + ". Ending connection.");
request = "End Connection";
out.write(request.getBytes());
in.close();
out.close();
socket.close();
System.exit(0);
} else {
System.out.println("Message received: " + request);
request = calculatePi(request);
System.out.println("Output: " + request);
out.write(request.getBytes());
}
} catch (IOException ex) {
System.out.println("Unable to get streams from client");
} finally {
try {
in.close();
out.close();
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("Welcome. IP address is: " + getIP());
ServerSocket server = null;
try {
server = new ServerSocket(PORT_NUMBER);
while (true) {
new ServerTest(server.accept());
}
} catch (IOException ex) {
System.out.println("Unable to start server.");
} finally {
try {
if (server != null)
server.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static String getIP() {
String ip = "";
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
// *EDIT*
if (addr instanceof Inet6Address) continue;
ip = addr.getHostAddress();
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
return ip;
}
and this is my client side code on device:
public class MainActivity extends AppCompatActivity {
TextView piResultTextView;
EditText addressEditText, messageEditText;
Button connectButton;
Handler handler = new Handler();
Results results;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
results = new Results();
addressEditText = findViewById(R.id.AddressEditText);
messageEditText = findViewById(R.id.MessageEditText);
connectButton = findViewById(R.id.ConnectButton);
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
connect();
}
});
piResultTextView = findViewById(R.id.PiResultTextView);
}
public void connect() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
String hostAddress = addressEditText.getText().toString();
int port = 8000;
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(hostAddress, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
Toast.makeText(getApplicationContext(), "Unknown host: " + hostAddress, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to get streams from server", Toast.LENGTH_SHORT).show();
}
String input = messageEditText.getText().toString();
try {
out.println(input);
results.pi = in.readLine();
handler.post(new Runnable() {
#Override
public void run() {
piResultTextView.setText(results.pi);
}
});
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to read input stream from server", Toast.LENGTH_SHORT).show();
}
try {
out.close();
in.close();
echoSocket.close();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error closing streams", Toast.LENGTH_SHORT).show();
}
}
});
thread.start();
}
}

How to make a consistent WIFI connection in android

In my new android app, I have made a direct tcp connection to a device with specific IP and port, all working fine. Issue here is when Wifi disconnect it does not reconnect or send data again.
Inside my code below, I have a class Client.java and MainActivity.java below.
How can I do this?
#####################################################
public class Client extends AsyncTask<String, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
Socket socket = null; Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse = textResponse;
}
#Override
protected Void doInBackground(String... params) {
String str = params[0];
try {
smtpSocket = new Socket(dstAddress, dstPort);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = smtpSocket.getInputStream();
//smtpSocket.
/* 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");
}
//textResponse.setText(response);
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
if (smtpSocket != null && os != null ) {
try {
os.writeBytes(str);
String responseLine;
while ((responseLine = is.readLine()) != null) {
System.out.println("Server: " + responseLine);
if (responseLine.indexOf("Ok") != -1) {
break;
}
}
//os.close();
//is.close();
//smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IO-Exception: " + e);
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//textResponse.setText("dweewed");
super.onPostExecute(result);
//super.cancel(true);
}
public void sendToPort(String str) throws IOException {
if (smtpSocket != null && os != null ) {
try {
os.writeBytes(str);
// os.close();
// is.close();
// smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}
#############################################################
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button buttonConnect, buttonClear;
TextView response;
Client myClient;
String editTextAddress = "10.0.1.50";
Integer editTextPort = 48;
boolean keepalive = true;
ConnectivityManager connManager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myClient = new Client(editTextAddress, editTextPort, response);
connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
buttonConnect = (Button) findViewById(R.id.btnconnect);
buttonClear = (Button) findViewById(R.id.clear);
response = (TextView) findViewById(R.id.feedback);
buttonConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
response.setText("");
String dat = "Open";
try {
//String dat = "sec rfdgdf";
dat = dat + "\r\n";
myClient.sendToPort(dat);
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
response.setText("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
});
}
#Override
public void onResume(){
super.onResume();
response.setText("Resum`enter code here`e connected!");
}
}
You can implement the reconnect logic in the callback of registerNetworkCallback in the ConnectivityManager
The code you provided doesn't use connManager

Server Ip at Client side using Sockets

I need to create an application using android socket level programming, I created a connection between server and client but I need to show waiting server IP list at client side and select one IP from the list and establish a connection between them.
Here is my code for server side
public class Server extends AppCompatActivity {
private static final String TAG = "ServerActivity";
private TextView tvServerStatus;
private TextView recievemsg;
InetAddress receiverAddress;
public static String SERVERIP = "";
DatagramSocket datagramSocket;
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
Handler updateConversationHandler;
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
updateConversationHandler = new Handler();
tvServerStatus = (TextView) findViewById(R.id.tvServerStatus);
recievemsg=(TextView)findViewById(R.id.send_msg);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
try {
datagramSocket = new DatagramSocket(8080);
byte[] buffer = "0123456789".getBytes();
byte[] address=SERVERIP.getBytes();
receiverAddress = InetAddress.getByAddress(address);
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, receiverAddress, 8080);
datagramSocket.send(packet);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getLocalIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
public class ServerThread implements Runnable {
#Override
public void run() {
try {
Log.e(TAG, "Server IP: " + SERVERIP);
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Listening On Ip: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (!Thread.currentThread().isInterrupted()) {
{
try {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(client);
new Thread(commThread).start();
// Log.e(TAG, "Client Socket: " + client);
// new Clients_Handle(client, ROOT_DIRECTORY).start();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
tvServerStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
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) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
recievemsg.setText(recievemsg.getText().toString() + "Client Says: " + msg + "\n");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
Log.e(TAG,"Socket Closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here is my client side code
public class Clientss extends AppCompatActivity {
private static final String TAG = "Client_Activity";
private EditText etServerIp;
private EditText etMsg;
private Button btnConnectClients;
private Button btnSendMsg;
private TextView textIn;
private String serverIpAddress = "";
private String t;
private boolean connected = false;
DatagramSocket datagramSocket;
DatagramPacket packet;
private Socket socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clientss);
Log.e(TAG, "ONCREATE METHOD");
textIn = (TextView)findViewById(R.id.txt_msg);
initializations();
eventClickListener();
try {
datagramSocket = new DatagramSocket(8080);
byte[] buffer = new byte[10];
packet = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(packet);
byte[] buff = packet.getData();
textIn.setText(buff.toString());
System.out.println("this is incoming ip"+buff.toString());
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// textIn.setText(t);
}
private void eventClickListener() {
btnConnectClients.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = etServerIp.getText().toString().trim();
connectsClient();
}
}
});
btnSendMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = etMsg.getText().toString().trim();
ClientResponseTask clientResponseTask=new ClientResponseTask(msg);
clientResponseTask.execute();
}
});
}
private void connectsClient() {
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
private void initializations() {
etServerIp = (EditText) findViewById(R.id.etServerIp);
etMsg = (EditText) findViewById(R.id.etMsg);
btnSendMsg = (Button) findViewById(R.id.btnMsgSend);
btnConnectClients = (Button) findViewById(R.id.btnConnect);
}
private class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.e(TAG, "C: Connecting...");
socket = new Socket(serverAddr, Server.SERVERPORT);
System.out.println("this is socket"+socket);
connected = true;
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
//showToast("");
Log.e(TAG, "C: Connected..." + socket);
} catch (Exception e) {
Log.e(TAG, "C: Error", e);
connected = false;
}
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
if(msg.arg1 == 1)
Toast.makeText(getApplicationContext(),"Connected...", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onDestroy() {
if (socket != null) try {
socket.close();
Log.e(TAG, "C: Socket Closed.");
} catch (IOException e) {
e.printStackTrace();
} finally
{
try
{
socket.close();
}
catch(Exception e){}
}
super.onDestroy();
}
protected class ClientResponseTask extends AsyncTask<Void,Void,Void> {
String msg;
ClientResponseTask(String msg){
this.msg=msg;
}
#Override
protected Void doInBackground(Void... params) {
if (connected) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(msg);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
Log.e(TAG, "Error", e);
}
}
else {
connectsClient();
}
return null;
}
}
}
Please help me to find a solution.

Unable to establish socket connect between two different android devices at different locations with different service providers

I am trying to establish a socket connection between two different devices at different places. I am using Airtel SIM on my android device. I am running following code on the device:
public class MainActivity extends Activity
{
Context context;
TextView info, infoip, msg;
String message = "";
ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
Sql s = new Sql(context);
info = (TextView) findViewById(R.id.info);
infoip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
new GetPublicIPTask().execute();
}
private class SocketServerThread extends Thread
{
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run()
{
try
{
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
info.setText("Port: " + serverSocket.getLocalPort());
}
});
while (true)
{
Socket socket = null;
try
{
socket = serverSocket.accept();
}
catch (Exception e)
{
e.printStackTrace();
}
count++;
message += "#" + count + " from " + socket.getInetAddress() + ":" + socket.getPort() + "\n";
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(socket, count);
socketServerReplyThread.run();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread
{
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c)
{
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run()
{
OutputStream outputStream;
String msgReply = "Hello client " + cnt;
try
{
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += "replied: " + msgReply + "\n";
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg.setText(message);
}
});
}
catch (IOException e)
{
e.printStackTrace();
message += "Exception! " + e.toString() + "\n";
}
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
msg.setText(message);
}
});
}
}
public class GetPublicIPTask extends AsyncTask<String, Integer, String>
{
ProgressDialog progressDialog;
String serverResponse = "";
public GetPublicIPTask()
{
progressDialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute()
{
if (!NetWorkInfo.isOnline(context))
{
Toast.makeText(context, "No Internet Connection", Toast.LENGTH_LONG).show();
return;
}
progressDialog.setMessage("Getting IP");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... sUrl)
{
BufferedReader in = null;
int TIME_OUT = 1000 * 60 * 10;
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);
HttpConnectionParams.setSoTimeout(params, TIME_OUT);
HttpGet httppost = new HttpGet("http://checkip.dyndns.org");
httppost.setHeader("Content-Type", "application/json");
try
{
HttpResponse response = httpclient.execute(httppost);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null)
{
sb.append(line);
}
serverResponse = sb.toString();
return serverResponse;
}
catch (Exception ex)
{
Log.d("Socket Server", "StackTrace : " + ex.getStackTrace().toString());
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
return null;
}
#Override
protected void onPostExecute(String result)
{
if (progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
infoip.setText(serverResponse);
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
super.onPostExecute(result);
}
}
}
And from terminal I am hitting the mobile app:
telnet publicIpAddress 8080
Same process working in local network, but not working in mobile networks.

Start Activity from Class in new Thread

Basically the idea is I check to see if the web session is still valid, if not I start the main activity which logs the user in automatically.
I have this working, not sure if it's the best way to do it. If anyone has a better way please let me know.
Thanks
Useage:
#Override
public void onResume() {
super.onResume();
new LoginCheck(this,new Intent(this,MyActivity.class));
}
The Class
public class LoginCheck extends Application {
Intent home;
Activity activity;
public LoginCheck(Activity activity, Intent home) {
this.activity = activity;
this.home = home;
new Check().execute();
}
public class Check extends AsyncTask {
#Override
protected Object doInBackground(Object... objects) {
try {
InputStream is = null;
String result = "";
JSONObject jArray = null;
PersistentCookieStore myCookieStore = new PersistentCookieStore(MyApp.getAppContext());
//http post
DefaultHttpClient mClient = AppSettings.getClient();
try {
HttpPost request = new HttpPost(MyApp.getServiceUrl() + "/Api/Login/AmILoggedIn");
mClient.setCookieStore(myCookieStore);
HttpResponse response = mClient.execute(request);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
final String r = result;
final Intent i = home;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject j = new JSONObject(r);
if (!j.getBoolean("Success")) {
try {
activity.startActivity(i);
} catch (Exception e) {
Log.e("log_tag", e.getMessage());
}
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
});
return true;
} catch (Exception e) {
}
return null;
}
}
}
Here is the cleaned up version
Use:
new LoginCheck() {
#Override
public void LoggedIn() {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void LoggedOut() {
//To change body of implemented methods use File | Settings | File Templates.
}
};
Class
public abstract class LoginCheck {
public LoginCheck(){
new Check().execute(true);
}
public class Check extends AsyncTask<Boolean,Boolean,Boolean>{
#Override
protected Boolean doInBackground(Boolean... objects) {
JSONStringer jsonSend = null;
try {
jsonSend = new JSONStringer()
.object()
.endObject();
} catch (JSONException e) {
Log.e("log_tag", "Error creating Json " + e.toString());
}
JSONObject result = JsonPost.postJSONtoURL(MyApp.getServiceUrl() + "/Api/Login/AmILoggedIn", jsonSend);
try {
if (result.getBoolean("Success")) {
return true;
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
try {
if (!result.getBoolean("Success")) {
return false;
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return false;
}
#Override
protected void onPostExecute(Boolean result){
if(result)
LoggedIn();
if(!result)
LoggedOut();
}
}
public abstract void LoggedIn();
public abstract void LoggedOut();
}

Categories