嗯,它在我的android studio模拟器上运行得非常好,但当我尝试在手机上运行它时,它只会崩溃。 我只想发送一个号码到服务器,并获得我需要的数据的响应。所以这是我的代码,这样做:当我尝试向服务器发送请求时,我的应用崩溃了
thread = new Thread() {
@Override
public void run() {
//server stuff
try {
//Connecting
if(!userClass.equals("")) {
Log.i(debugString, "Attempting to connect to server");
socket = new Socket(hostname, portnumber);
Log.i(debugString, "Connection established!");
BufferedWriter bw = new BufferedWriter((new OutputStreamWriter(socket.getOutputStream())));
bw.write("" + userClass);
bw.newLine();
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
input = br.readLine();
}
} catch (IOException e) {
Log.e(debugString, e.getMessage());
} finally {
threadComplete = true;
}
}
};
thread.start();
while(!threadComplete)
continue;
然后我只是每当我想对我的要求一样,更新的信息使用此线程:
String getUserClass = userClass;
if(!getUserClass.equals(""))
{
threadComplete = false;
userClass = getUserClass;
thread.start();
while (!threadComplete)
continue;
changes.setText(input);
}
else Toast.makeText(this, "Error, choose your class", Toast.LENGTH_SHORT).show();
顺便说一句,在每次结束线程(在模拟器上因为我的手机崩溃),我得到一个消息: Skipped 91 frames! The application may be doing too much work on its main thread.
,我有一个问题,我也用IntentService
至后台运行我的应用程序服务,很明显,我不希望它永远不断运行,所以我做了一个循环,在每个循环的末尾包含一个wait()
命令,但问题是当我将时间设置为等待超过3000毫秒左右时,服务崩溃。 我的后台服务代码:
synchronized (this) {
int count = 0;
while (count<4) {
try {
wait(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (notifications && !userClass.equals("")) {
new Thread() {
@Override
public void run() {
//server stuff
try {
//Connecting
if (!userClass.equals("")) {
Log.i("debug", "Attempting to connect to server");
socket = new Socket(hostname, portnumber);
Log.i("debug", "Connection established!");
BufferedWriter bw = new BufferedWriter((new OutputStreamWriter(socket.getOutputStream())));
bw.write("" + userClass);
bw.newLine();
bw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
input = br.readLine();
}
} catch (IOException e) {
Log.e("debug", e.getMessage());
} finally {
complete = true;
}
}
}.start();
while (!complete)
continue;
Toast.makeText(this, "" + input, Toast.LENGTH_SHORT).show();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.chanka)
.setContentTitle("ביטול שיעורים: ")
.setContentText(input);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
mNotificationId++;
Toast.makeText(this, "" + input, Toast.LENGTH_SHORT).show();
count++;
}
}
}
请确保'hostname url'是你的私有IP – samirk433
@ samir.k433这不是问题,连接工作,我也做了java服务器。问题是,只有当我使用我的PC模拟器时,连接才起作用,当我尝试在我的LG G3上启动它时,它只会在线程启动时崩溃。 也是我得到的问题:'跳过91帧!该应用程序可能在其主线程上做了太多工作。“在日志中,所以我认为我的程序效率不够高,而且为手机运行起来很沉重,而我只是不知道如何使它工作并且更高效。 –