嗯,它在我的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幀!該應用程序可能在其主線程上做了太多工作。「在日誌中,所以我認爲我的程序效率不夠高,而且爲手機運行起來很沉重,而我只是不知道如何使它工作並且更高效。 –