Results 1 to 1 of 1
  1. #1
    cjdelphi is offline Member
    Join Date
    Jan 2014
    Posts
    1
    Rep Power
    0

    Unhappy How to re-run a thread? (sockets involved)

    Java Code:
    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;
    
    
    
    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);
    	  	    // The activity is no longer visible (it is now "stopped")
    	}
    	
    	@Override
    	public void onStart(){
    	 super.onStart();
    	/*  if (networktask!=null)
    		  if (networktask.getStatus() == AsyncTask.Status.FINISHED) 
    	        networktask.execute();
    		  else
    		  {
         	     networktask = new NetworkTask(); //New instance of NetworkTask
                 networktask.execute();
    		  
    		  }
    	  //   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();
                 networktask.cancel(true);          	
                 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;
    	}
    
    }



    Basically, this code is working, there's 6 buttons, i've set permissions for internet, it runs, the buttons work no problem, all fine...



    except for one small thing...


    This is driving me insane now, when you run it, it works.. when you close it or the application goes to the background
    onStop(); happens and the thread seems to be destroyed.

    using

    Java Code:
    	@Override
    	protected void onStop() {
    	    super.onStop();
    	   //
    	//    networktask.cancel(true);
    	  	    // The activity is no longer visible (it is now "stopped")
    	}
    	
    	@Override
    	public void onStart(){
    	 super.onStart();
    	/*  if (networktask!=null)
    		  if (networktask.getStatus() == AsyncTask.Status.FINISHED) 
    	        networktask.execute();
    		  else
    		  {
         	     networktask = new NetworkTask(); //New instance of NetworkTask
                 networktask.execute();
    		  
    		  }
    	  //   networktask.execute();
    	   * */
    	  
    	}

    the idea is to Resume the thread, or restart the thread (without it crashing) when it returns back to focus.



    Yeah the code is messy because I'm only half knowing what i'm doing, i got a feeling it's something simple like thread.resume or thread.destroy and then resume???




    Anyway - new to the forum, Thank you for help in advance, nice to see such a large community (PS i added {CODE} {/CODE} (but with [ and ] and it's not working?)
    Last edited by cjdelphi; 01-08-2014 at 10:43 AM.

Similar Threads

  1. Out of memory sockets and thread?
    By mrhid6 in forum Threads and Synchronization
    Replies: 19
    Last Post: 10-11-2011, 12:25 AM
  2. SORT list on items where frequencies are involved
    By emgee in forum Java Applets
    Replies: 1
    Last Post: 11-14-2010, 02:42 PM
  3. Replies: 6
    Last Post: 11-18-2009, 11:39 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •