Wednesday, December 19, 2012

[android-developers] Re: Problem exit,close my application...

Change this:


runnable.run();


to this:


new Thread(runnable).start();




On Wednesday, December 19, 2012 5:25:01 AM UTC-6, Antonis Kanaris wrote:

    I make an application download data from web send to bluetooth,listen bluetooth and upload to web with loop....but when push button close my apk freeze...no work...


        /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2);
 
        //txt=(TextView)findViewById(R.id.txt);
        myLabel = (TextView)findViewById(R.id.label);
        temptext = (TextView)findViewById(R.id.temptxt);
       
        SharedPreferences preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
       
           strValue = preferences.getString("Url","");
              TextView text = (TextView) findViewById(R.id.txt1);
              text.setText(strValue);
           strValue2 = preferences.getString("DevName","");
              TextView text2 = (TextView) findViewById(R.id.txt2); 
              text2.setText(strValue2);       
             
             
    
    }
   
    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
          String response = "";
          for (String url : urls) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            try {
              HttpResponse execute = client.execute(httpGet);
              InputStream content = execute.getEntity().getContent();

              BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
              String s = "";
              while ((s = buffer.readLine()) != null) {
                response += s;
              }

            } catch (Exception e) {
              e.printStackTrace();
            }
          }
          return response;
        }

        @Override
        protected void onPostExecute(String result) {
            TextView text3 = (TextView) findViewById(R.id.txt3);
            text3.setText(result);
            try {
                sendData(result);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }
      }

  
   
    protected void onStart() {
        super.onStart();
       
        try
        {        
            findBT();
            openBT();                           
        }
        catch (IOException ex) { }
       
        runnable.run();
 
  }

  private Runnable runnable = new Runnable()
  {

      public void run()
      {
            
              DownloadWebPageTask task = new DownloadWebPageTask();
              task.execute(new String[] { strValue });//Download data on/off
             
              beginListenForData();//Listen Bluetooth temperature
             
              SimpleHttpPut task2 = new SimpleHttpPut();
                task2.execute(new String[] { urlt,data });//Upload data class
       
        if(work){  handler.postDelayed(this, 30000);}//Refresh page time
      }
  };
 
  void findBT()
  {
      mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      if(mBluetoothAdapter == null)
      {
          myLabel.setText("No bluetooth adapter available");
      }
    
      if(!mBluetoothAdapter.isEnabled())
      {
          //mBluetoothAdapter.enable();
          Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
          startActivityForResult(enableBluetooth, 0);
         
         
      }
    
      Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
      if(pairedDevices.size() > 0)
      {
          for(BluetoothDevice device : pairedDevices)
          {
              if(device.getName().equals(strValue2))
              {
                  mmDevice = device;
                  break;
              }
          }
      }
      myLabel.setText("Bluetooth Device Found");
  }
 
  void openBT() throws IOException
  {
      UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
      mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);      
      mmSocket.connect();
      mmOutputStream = mmSocket.getOutputStream();
      mmInputStream = mmSocket.getInputStream();
    
     // beginListenForData();
    
      myLabel.setText("Bluetooth Opened");
  }
 
  void sendData(String msg) throws IOException
  {
    
      msg += "\n";
      mmOutputStream.write(msg.getBytes());
      myLabel.setText("Data Sent");
  }
 
  void beginListenForData()
  {
      final Handler handler = new Handler();
      final byte delimiter = 10; //This is the ASCII code for a newline character
     
      stopWorker = false;
      readBufferPosition = 0;
      readBuffer = new byte[1024];
      workerThread = new Thread(new Runnable()
      {
          public void run()
          {               
             while(!Thread.currentThread().isInterrupted() && !stopWorker)
             {
                  try
                  {
                      int bytesAvailable = mmInputStream.available();                       
                      if(bytesAvailable > 0)
                      {
                          byte[] packetBytes = new byte[bytesAvailable];
                          mmInputStream.read(packetBytes);
                          for(int i=0;i<bytesAvailable;i++)
                          {
                              byte b = packetBytes[i];
                              if(b == delimiter)
                              {
                                  byte[] encodedBytes = new byte[readBufferPosition];
                                  System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                    //final String data = new String(encodedBytes, "US-ASCII");
                                    data = new String(encodedBytes, "US-ASCII");
                                   
                                   
                                  readBufferPosition = 0;
                                 
                                  handler.post(new Runnable()
                                  {
                                      public void run()
                                      {
                                          temptext.setText(data);
                                         
                                      }
                                 });
                              }
                              else
                              {
                                  readBuffer[readBufferPosition++] = b;
                              }
                          }
                      }
                  }
                  catch (IOException ex)
                  {
                      stopWorker = true;
                  }
             }
         }
      });

      workerThread.start();
  }
 
  void close() throws IOException
  {
      work=false;
        stopWorker = true;
      mmOutputStream.close();
      mmInputStream.close();
      mmSocket.close();
      //mBluetoothAdapter.disable();
      myLabel.setText("Bluetooth Closed");
      finish();
      System.exit(0);
  }
   
    public void Setup(View view)
    {
        work=false;
       
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
    }

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

No comments:

Post a Comment