1. Download our Official Android App: Forums for Android!

Apps Async Threading issue.

Discussion in 'Android Development' started by cjdelphiq, Jan 8, 2014.

  1. cjdelphiq

    cjdelphiq Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    4
    Joined:
    Jan 8, 2014

    Jan 8, 2014
    4
    0
    5
    basically, I'm using Async for my socket, the idea is the applications runs, i press buttons, it sends commands to my pc, the program works fine until that is...

    it loses focus, at which point everything i've tried does not bring the thread or socket back to life, all i want to do is re-create the socket when the application gets focus.

    [HIGH]
    package com.example.craigs.remote;

    import java.io.IOException;
    import java.io.InputStream;
    import java.io_OutputStream;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.net.SocketAddress;

    import android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;


    /*Procedure tForm1.ProcessData();
    var
    tmp,Str: String;
    Begin
    Str:=S;
    case S[1] of
    'm': ArduinoCmd1; //centre mouse
    'k': ArduinoCmd2; //space bar
    'a': ArduinoCmd3; //left mouse click
    'A': ArduinoCmd4; //left double click
    'M': ArduinoCmd5; //Enigma
    'S': ArduinoCmd6; //Shutdown power off
    End;
    End;
    */




    public class MainActivity extends Activity {
    Button b1,b5;
    Button b2,b3,b4;
    Button b6;
    NetworkTask networktask;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b1 = (Button)findViewById(R.id.button1);
    b2 = (Button)findViewById(R.id.button2);
    b3 = (Button)findViewById(R.id.button3);
    b4 = (Button)findViewById(R.id.button4);
    b5 = (Button)findViewById(R.id.button5);
    b6 = (Button)findViewById(R.id.button6);
    // networktask = new NetworkTask();
    networktask = new NetworkTask(); //New instance of NetworkTask
    networktask.execute();



    b6.setOnClickListener(new OnClickListener(){
    public void onClick(View view) {
    onBackPressed();
    finish();
    // super.onBackPressed();

    }});



    b1.setOnClickListener(new OnClickListener(){

    /// String testServerName = "192.168.1.10";
    // int port = 8899;

    public void onClick(View view)
    {
    networktask.SendDataToNetwork("m");
    //m mouse centre


    ////////
    }});









    b2.setOnClickListener(new OnClickListener(){


    public void onClick(View view)
    {

    networktask.SendDataToNetwork("k");
    //k


    ////////
    }});





    b3.setOnClickListener(new OnClickListener(){

    public void onClick(View view)
    {

    // pw.write("a");
    networktask.SendDataToNetwork("a");
    ////////
    }});



    b4.setOnClickListener(new OnClickListener(){

    public void onClick(View view)
    {
    //A
    networktask.SendDataToNetwork("A");
    ////////
    }});



    b5.setOnClickListener(new OnClickListener(){

    public void onClick(View view)
    {

    networktask.SendDataToNetwork("S");
    // pw.write("S");


    ////////
    }});





    }


    public class NetworkTask extends AsyncTask<Void, byte[], Boolean> {
    Socket nsocket; //Network Socket
    InputStream nis; //Network Input Stream
    OutputStream nos; //Network Output Stream

    @Override
    protected void onPreExecute() {
    Log.i("AsyncTask", "onPreExecute");
    }

    @Override
    protected Boolean doInBackground(Void... params) { //This runs on a different thread
    boolean result = false;
    try {
    Log.i("AsyncTask", "doInBackground: Creating socket");
    SocketAddress sockaddr = new InetSocketAddress("192.168.1.10", 8899);
    nsocket = new Socket();
    nsocket.connect(sockaddr, 5000); //10 second connection timeout
    if (nsocket.isConnected()) {
    nis = nsocket.getInputStream();
    nos = nsocket.getOutputStream();
    Log.i("AsyncTask", "doInBackground: Socket created, streams assigned");
    Log.i("AsyncTask", "doInBackground: Waiting for inital data...");
    byte[] buffer = new byte[4096];
    int read = nis.read(buffer, 0, 4096); //This is blocking
    while(read != -1){
    byte[] tempdata = new byte[read];
    System.arraycopy(buffer, 0, tempdata, 0, read);
    publishProgress(tempdata);
    Log.i("AsyncTask", "doInBackground: Got some data");
    read = nis.read(buffer, 0, 4096); //This is blocking
    }
    }
    } catch (IOException e) {
    e.printStackTrace();
    Log.i("AsyncTask", "doInBackground: IOException");
    result = true;
    } catch (Exception e) {
    e.printStackTrace();
    Log.i("AsyncTask", "doInBackground: Exception");
    result = true;
    } finally {
    try {
    nis.close();
    nos.close();
    nsocket.close();

    } catch (IOException e) {
    e.printStackTrace();
    } catch (Exception e) {
    e.printStackTrace();
    }
    Log.i("AsyncTask", "doInBackground: Finished");
    }
    return result;
    }

    public void SendDataToNetwork(String cmd) { //You run this from the main thread.
    try {
    if (nsocket.isConnected()) {
    Log.i("AsyncTask", "SendDataToNetwork: Writing received message to socket");
    nos.write(cmd.getBytes());
    } else {
    Log.i("AsyncTask", "SendDataToNetwork: Cannot send message. Socket is closed");
    }
    } catch (Exception e) {
    Log.i("AsyncTask", "SendDataToNetwork: Message send failed. Caught an exception");
    }
    }

    @Override
    protected void onProgressUpdate(byte[]... values) {
    if (values.length > 0) {
    Log.i("AsyncTask", "onProgressUpdate: " + values[0].length + " bytes received.");
    // textStatus.setText(new String(values[0]));
    }
    }
    @Override
    protected void onCancelled() {
    Log.i("AsyncTask", "Cancelled.");
    // btnStart.setVisibility(View.VISIBLE);
    }
    @Override
    protected void onPostExecute(Boolean result) {
    if (result) {
    Log.i("AsyncTask", "onPostExecute: Completed with an Error.");
    // textStatus.setText("There was a connection error.");
    } else {
    Log.i("AsyncTask", "onPostExecute: Completed.");
    }
    // btnStart.setVisibility(View.VISIBLE);
    }
    }

    @Override
    protected void onStop() {
    super.onStop();
    networktask.cancel(true);
    //
    // networktask.cancel(true);
    // The activity is no longer visible (it is now "stopped")
    }

    @Override
    public void onStart(){
    super.onStart();
    /* if (networktask!=null)
    if (networktask.isCancelled()==true)
    networktask.execute();
    else
    {
    networktask = new NetworkTask(); //New instance of NetworkTask
    networktask.execute();

    }
    // networktask.execute();
    */
    }


    @Override
    public void onRestart()
    {
    super.onRestart();
    networktask.cancel(true);
    networktask = new NetworkTask();
    networktask.execute();

    }


    @Override
    public void onBackPressed() {
    // if(childView != null && parentLayout.getChildCount()==2){
    // childView.stopLoading();
    // parentLayout.removeViewAt(parentLayout.getChildCount()-1);
    // if(webView.getVisibility() == View.GONE)
    // webView.setVisibility(View.VISIBLE);
    super.onBackPressed();
    }

    @Override
    protected void onDestroy() {

    super.onDestroy();

    finish();
    //In case the task is currently running
    }





    @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;
    }

    }

    [/HIGH]



    So how do i get this Async thread active again once the app loses focus?..



    Thanks in advance (I tried placing execute for Async inside the onStart but it crashed)
     

    Advertisement

  2. cjdelphiq

    cjdelphiq Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    4
    Joined:
    Jan 8, 2014

    Jan 8, 2014
    4
    0
    5
    oh and i pressed the # key for the CODE tag, but instead HIGH appears (bug?)
     

Share This Page

Loading...