- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对 java 和 Android 开发都很陌生,我正在设计一个 android 客户端来向服务器发送消息,并从服务器接收回消息。它只执行几个功能,首先它会查询服务器的初始状态,然后它会使用该状态更新一个按钮,以及一个充电符号来说明充电器是否正在充电。我已经让所有的通信代码都可以工作,线程似乎可以很好地发送和接收消息,但是线程之外的变量没有被更新,如果我关闭服务器连接,客户端将保持连接打开,好像服务器还在那里。谁能给我一些建议来解决我的问题?
package charger.app;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class ChargeTabActivity extends Activity {
String serverIp = "192.168.6.120"; //server Ip address
private static String preqon = "control:Charger:1\r\n"; //sets connection to turn charger on
private static String preqoff = "control:Charger:0\r\n"; //Turn charger off
public boolean connected = false; //connection
//set up buttons
private ImageButton chargeOnOff;
private ImageButton connectButton;
//Set it so that Client Functions can be accessed from main program
ClientFunctions functions = new ClientFunctions();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initialize UI
setContentView(R.layout.main);
//declare buttons for listeners, and display changes
connectButton = (ImageButton)findViewById(R.id.connectButton);
connectButton.setOnClickListener(connectButtonListener);
chargeOnOff = (ImageButton)findViewById(R.id.chargeOnOff);
chargeOnOff.setOnClickListener(chargeOnOffListener);
Button chargeStatus = (Button)findViewById(R.id.chargeStatus);
////set up strict mode off/////
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/*Listens to see if the connect button is pressed, if it is connected it will
* display connected, else it will try and connect*/
private OnClickListener connectButtonListener = new OnClickListener()
{
public void onClick(View v)
{
if (connected)
{
toast("I am connected");
}
else
{
toast("I am not connected");
}
}
};
/*Listens to see if the Charge on Off Button is pressed, if it is charging it will
* send a request to charge, else it will send a request to stop the charge*/
private OnClickListener chargeOnOffListener = new OnClickListener()
{
public void onClick(View v)
{
//ask server
try {
functions.updateStatus(); //updates the charger status
} catch (IOException e) {
Log.e("Client","Trouble querying",e);
e.printStackTrace();
}
//send message to turn server on or off
if (functions.chargeStatNumber != 0)
{
try {
functions.sendMessage(preqoff);
chargeOnOff.setImageResource(R.drawable.charge_on);
toast("Turning Charger off");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end if
else
{
try {
functions.sendMessage(preqon);
chargeOnOff.setImageResource(R.drawable.charge_off);
toast("Turning Charger on");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} //end else
Log.d("ClientActivity", "Charge Button hit" );
//ask server about its status
try {
functions.updateStatus(); //updates the charger status
} catch (IOException e) {
Log.e("Client","Trouble querying",e);
e.printStackTrace();
}
}
};
/////When Application Starts
@Override
public void onStart()
{
super.onStart();
Thread cThread = new Thread(new serverThread()); //Starts the thread that initiates communications
cThread.start();
};
////////On Pause//////This is when a user makes another app, the center point of attention
@Override
public void onPause() {
super.onPause();
functions.closeConnection();
};
//////On Resume/////This is used for when an app exits, and then the user brings it back
@Override
public void onResume() {
super.onResume();
};
//////On Destroy//////////
@Override
public void onDestroy() {
super.onDestroy();
functions.closeConnection();
};
//toast messages
public void toast(String toastMessage)
{
Toast.makeText(DelphiChargeTabActivity.this, toastMessage,
Toast.LENGTH_LONG).show();
};
//Thread to run and receive network connections
public class serverThread implements Runnable
{
public boolean connected = false; //connection
public void run() //runs the thread
{
try
{
functions.connectToServer(serverIp); //connects to server
connected = true;
while (connected)
{
try
{
connectButton.setImageResource(R.drawable.blue_car);
functions.getStreams(); //establish stream connections
functions. updateStatus(); //updates the status of the server
//checkChangeChargeButton(); //sets initial state for charge button
try
{
Thread.sleep(2500);
}
catch ( InterruptedException interruptedException )
{
functions.displayMessage( "\nThread exception" );
} // end catch
}
catch (IOException e)
{
Log.e("Client","Trouble Getting Streams",e);
}
}//end while
}//end try
catch (Exception e)
{
Log.e("Client", "Error Connecting", e);
connected = false;
connectButton.setImageResource(R.drawable.red_car);
}
}; //end run
}; //end serverThread
public void checkChangeChargeButton()
{
if (functions.chargeStatNumber != 0)
{
chargeOnOff.setImageResource(R.drawable.charge_on);
}
else
{
chargeOnOff.setImageResource(R.drawable.charge_off);
}
};
} //This is the Activity close bracket
这是我的函数方法的代码
package charger.app;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import android.util.Log;
public class ClientFunctions
{
private String message;
private String server;
public Socket sock;
private PrintWriter writer;
private DataInputStream inStream;
public Boolean connected;
private String encode = "UTF8";
public byte[] chargerstat;
public int chargeStatNumber; //Used to set the array byte 15 to an int
//inquires server for status of charge
public void updateStatus() throws IOException
{
//Prompt user for server command
System.out.println("Sending request for Charger status data.");
String serverMessage = "meas:Charger?\r\n";
// send the message
sendMessage("meas:Charger?\r\n");
System.out.println();
displayMessage(serverMessage + "sent");
// now receive the message
receiveMessage();
displayMessage("Receive complete");
};
public void connectToServer(String serverIp) throws IOException //Server IP is sent in main app as String "serverIp"
{
//set server IP
//display logcat trying to connect
displayMessage("\nTrying to Connect");
//Start Socket Connection
sock = new Socket( InetAddress.getByName( serverIp ), 18088);
//Display connected
displayMessage( "\nConnected to: " +
sock.getInetAddress().getHostName() );
};
public void getStreams() throws IOException
{
//Set up PrintWriter
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())),true);
writer.flush();
//Set Up I
inStream = new DataInputStream(sock.getInputStream());
//display Message Got I/O
displayMessage("\nGot IO Streams");
};
public void sendMessage(final String serverMessage) throws UnsupportedEncodingException
{
//set variable for message
message = serverMessage;
//sends message
writer.printf("%s", message);
writer.flush();
//display message sent
displayMessage("\nsent" /*+ serverMessage*/);
};
public static int getInt(byte[] array, int offset)
{
return
((array[offset+3] & 0xff) << 24) |
((array[offset+2] & 0xff) << 16) |
((array[offset+1] & 0xff) << 8) |
(array[offset] & 0xff);
}
public void receiveMessage() throws IOException
{
{
int c=0;
int i;
int seqcountval;
chargerstat = new byte[96];
i=0;
while(i < 96)
{
try
{
c = inStream.read();
chargerstat[i] = (byte)c;
}
catch ( IOException ioException )
{
ioException.printStackTrace();
} // end catch
// uncomment this to see each byte
//displayMessage(":" + i + " " + chargerstat[i]);
i++;
}
seqcountval = getInt(chargerstat, 76);
displayMessage("SeqCntr = " + seqcountval);
chargeStatNumber = chargerstat[15];
};
};
public void closeConnection()
{
//closes connections
displayMessage("\n\nClosing Connection");
try
{
writer.close();
inStream.close();
sock.close();
}
catch ( IOException ioException )
{
ioException.printStackTrace();
} // end catch
};
public void displayMessage( final String messageToDisplay )
{
new Runnable()
{
public void run() // updates displayArea
{
//change to log.d for android
System.out.println(messageToDisplay);
} // end method run
}; // end anonymous inner class
} // end method displayMessage
};
最佳答案
你为什么不使用 AsyncTask 而不是线程,它会更容易共享信息并且似乎适用于你正在尝试做的事情。
Using AsyncTask
AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.
http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html
ChargerActivity 中的“connected”变量与 ServerThread 中的不同,因此 ChargerActivity 的 connected 不会从线程更新。
关于java - Socket Client + Threading + Android + connection Status's,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9743305/
使用 caret::train() 运行逻辑回归模型时出现问题。LR = caret::train(Satisfaction ~., data= log_train, method = "glm",
我正在尝试将nginx容器作为我所有网站和Web服务的主要入口点。我设法将portainer作为容器运行,并且可以从互联网上访问它。现在,我正在尝试访问由另一个Nginx容器托管的静态网站,但这样做失
我有一个在 Windows XP SP3 x86 上运行的 Visual Studio 2008 C# .NET 3.5 应用程序。在我的应用程序中,我有一个事件处理程序 OnSendTask 可以同
我在 Eclipse 中创建了作为独立程序执行的此类,它可以毫无问题地连接所有 http URL(例如:http://stackoverflow.com),但是当我尝试连接到 https(例如 htt
我在我的 nginx 错误日志中收到大量以下错误: connect() failed (111: Connection refused) while connecting to upstream 我的
我正在尝试将新的 log4j2 与 Socket Appender 一起使用,但我有点不走运。这是我的 XML 配置文件:
我目前正在尝试寻找 Android 应用程序后端的替代方案。目前,我使用 php servlet 来查询 Mysql 数据库。数据库(Mysql)托管在我大学的计算机上,因此我无法更改任何配置,因为我
类MapperExtension有一些方法,before_insert, before_update, ...都有一个参数connection. def before_insert(self, map
嗨,我正在尝试更改位于连接库 (v 5.5) 中的文档的文档所有者,我仍在等待 IBM 的回复,但对我来说可能需要太长时间,这就是我尝试的原因逆向工程。 我尝试使用标准编辑器 POST 请求将编辑器更
我在 nginx( http://52.xx.xx.xx/ )上访问我的 IP 时遇到 502 网关错误,日志只是这样说: 2015/09/18 13:03:37 [error] 32636#0: *
我要实现 Connected-Component Labeling但我不确定我应该以 4-connected 还是 8-connected 的方式来做。我已经阅读了大约 3 种 Material ,但
我在Resources ->JMS ->Connection Factories下有两个连接工厂。 1) 连接工厂 2)集成连接工厂 我想修改两个连接工厂下连接池的最大连接数。资源 ->JMS ->连
我在将 mongoengine 合并到我的 django 应用程序时遇到问题。以下是我收到的错误: Traceback (most recent call last): File "/home/d
上下文 我正在关注 tutorial on writing a TCP server last week in Real World Haskell .一切顺利,我的最终版本可以正常工作,并且能够在
我在访问我的域时遇到了这个问题:我看到了我的默认 http500 错误 django 模板正在显示。 我有 gunicorn 设置: command = '/usr/local/bin/gunicor
我更换了电脑,并重新安装了所有版本:tomcat 8 和 6、netbeans 8、jdk 1.7、hibernate 4.3.4,但是当我运行 Web 应用程序时,出现此错误。过去使用我的旧电脑时,
您好,我是这个项目的新手,我在 CentOS7 ec2 实例上托管它时遇到问题。当我访问我的域时出现此错误: 2017/02/17 05:53:35 [error] 27#27: *20 connec
在开始之前,我已经查看了所有我能找到的类似问题,但没有找到解决我的问题的方法。 我正在运行 2 个 docker 容器,1 个用于 nginx,1 个用于 nodejs api。我正在使用 nginx
使用 debian 包将 kaa -iot 平台配置为单节点时。我收到以下错误。 himanshu@himpc:~/kaa/deb$ sudo dpkg -i kaa-node-0.10.0.deb
我是我公司开发团队的成员,担任管理员角色。我可以通过 https://developer.apple.com/ 访问团队的成员(member)中心 但是,当我尝试在 https://itunescon
我是一名优秀的程序员,十分优秀!