我有一个PlayerActivity
类和一个PlayerConnect
类。
[以前,我使用PlayerActivity
类来启动将运行PlayerConnect
的线程。我最近发现该线程行为不正常,建议使用服务(为此:IntentServices)。
问题:我的日志告诉我IP,名称和init为null,null,0,这不是事实,因为它们应该在开始启动之前设置。服务。日志还告诉我它无法连接到本地主机,我认为这是默认设置,因为它没有要尝试的设置IP。
我在意图中正确引用了PlayerConnect
类吗?
PlayerActivity:
public class PlayerActivity extends AppCompatActivity {
InetAddress hostIP;
String playerName;
int playerInitiative = -1;
boolean denied = false;
boolean started = false;
PlayerConnect playerConnect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!(playerName.equals("")) && playerInitiative > -1) {
try {
if (!(hostIPString.equals(""))) {
hostIP = InetAddress.getByName(hostIPString);
if(!(started)) {
playerConnect = new PlayerConnect();
playerConnect.SetHostIP(hostIP);
playerConnect.SetPlayerName(playerName);
playerConnect.SetPlayerInit(playerInitiative);
denied = playerConnect.GetDenied();
started = true;
}
else {
playerConnect.SetHostIP(hostIP);
playerConnect.SetPlayerName(playerName);
playerConnect.SetPlayerInit(playerInitiative);
denied = playerConnect.GetDenied();
}
if (denied)
{
started = false;
}
else
{
Intent playerConnectIntent =
new Intent(PlayerActivity.this, playerConnect.getClass());
startService(playerConnectIntent);
}
}
}
catch (Exception e) {
Log.i("LOG", e.toString());
}
}
}
});
}
}
PlayerConnect:
public class PlayerConnect extends IntentService {
public PlayerConnect() {
super("PlayerConnect");
}
InetAddress hostIP;
String playerName;
int playerInitiative;
boolean denied = false;
@Override
public void onHandleIntent(Intent intent) {
SendPlayerData(hostIP, playerName, playerInitiative);
}
private void SendPlayerData(InetAddress IP, String name, int init) {
try {
int port = 8080;
Socket socket = new Socket();
socket.connect(new InetSocketAddress(IP, port), 3000);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
if (socket.isConnected())
{
output.writeUTF(name);
output.writeInt(init);
output.close();
socket.close();
Log.i("LOG", "client socket connected");
}
if (socket.isClosed())
{
stopSelf();
Log.i("LOG", "client socket closed");
}
}
catch (Exception e) {
denied = true;
Log.i("LOG", e.toString());
Log.i("LOG", IP + name + init);
}
}
public void SetHostIP(InetAddress host)
{
hostIP = host;
}
public void SetPlayerName(String name)
{
playerName = name;
}
public void SetPlayerInit(int init)
{
playerInitiative = init;
}
public boolean GetDenied()
{
return denied;
}
}