Android Socket Thread在处理器上添加非常高的负载

时间:2012-11-26 21:34:38

标签: android multithreading sockets processor

我正在我的Galaxy S3上调试我的应用程序,每当我监视处理时......我注意到应用处理的负载非常高。应用程序处理有时达到80%,这是非常高的

以下是代码:

package com.example.socketclient;



import android.app.Activity;
import android.os.Bundle;

import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.OutputStreamWriter; 
import java.io.InputStreamReader;
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import android.util.Log; 

public class SocketCode extends Activity {
    private boolean connected = false;
    //private Handler handler = new Handler();
    public TextView txt;
    int doit=0;
    protected SocketCore Conn;
    public Button b;
    public EditText TextToSend;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_code);
        b = (Button)findViewById(R.id.button1);
        txt = (TextView)findViewById(R.id.textView1);
        TextToSend = (EditText)findViewById(R.id.editText1);
        //Conn = new SocketCore(this,txt);
        b.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                 Log.e("ErrorButton","Button Pressed Before Toggle"+doit);  
             doit=1;
             Log.e("ErrorButton","Button Pressed "+doit);
            }
        }); 

        Thread cThread = new Thread(new ClientThread());
        cThread.start();

    }
    public class ClientThread implements Runnable {
        Socket socket ;
String finall="",text;
PrintWriter out = null;
BufferedReader in = null;

        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName("192.168.0.150");
                Log.d("ClientActivity", "C: Connecting...");
                socket= new Socket(serverAddr,4444);
                connected = true;

                while (connected) {
                    try {



                      if(doit==1)
                      {
                          Log.e("ErrorButton","If");

                          out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); 
                        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));                

                        out.println(TextToSend.getText().toString());
                       finall="";
                        while ((text = in.readLine()) != null) {
                            finall += text;
                            Log.e("Test","Final: "+finall);
                          if(text=="quit")
                          {
                              socket.close();
                          }
                      Log.e("ClientActivity", "After Read "+doit+" "+finall);

                       break;
                      } 

                      doit=0;

                      Log.e("ClientActivity", "Out Of IF "+doit);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            txt.setText(finall);
                        }
                    });

                      }     



                    } catch (Exception e) {
                        Log.e("ClientActivity", "S: Error", e);
                    }

                }
                socket.close();
                txt.setText("Closed Socket");
                Log.d("ClientActivity", "C: Closed.");
            } catch (Exception e) {
                Log.e("ClientActivity", "C: Error", e);
                connected = false;
            }
        }

        public void ClientHandler(String Send)
        {
            try{
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                       .getOutputStream())), true);
           out.println(Send);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            finall = in.readLine();

            txt.setText(finall);
            }
            catch(IOException e)
            {txt.setText("Exception");}
        }


    }


}

2 个答案:

答案 0 :(得分:1)

CPU正在这样做,因为你正在运行一个不停的循环,它将runnables送入UI线程,因此CPU保持在非常高的负载下。相反,我建议您考虑使用推送策略而不是像GCM(Google云消息传递)这样的轮询策略,当您的服务器将新数据推送到设备上时,您的应用会被唤醒。如果这不是一个可能的解决方案,我会将轮询速率限制在较低的速率并将其限制为每分钟几次(或更少),在run()中定期使用Thread.sleep()以避免泛滥UI线程可运行。

答案 1 :(得分:0)

固定 使用Thread.Sleep(200);

while (connected) {
                    try {
                        Thread.sleep(200);
                        Log.e("ErrorButton","If");
                      if(doit==1)
                      {