私はandroid/phpプロジェクトに取り組んでいます。ユーザーが初期化関数を呼び出し、関数に ID を渡す Android 用のライブラリを作成しています。
次に、関数はサーバーに HTTP ポストを実行し、そこで ID が存在することをデータベースに確認します。サーバーからの応答に基づいて、初期化が完了したことを設定するか、初期化を完了できなかったことを示すエラーをログに記録するように設定する必要があります。
ただし、スレッドで投稿を実行する必要があるため、コードは次のコード行に直接落ちます。これは、初期化が失敗したことを意味します。では、スレッドが完了するまでコードの実行を一時停止するにはどうすればよいでしょうか。
以下は初期化関数です。
public static void Initialise(Context context, String appID)
{
appContext = context;
CritiMon.appID = appID;
isAppIdCorrect(appID);
if (appIdValid)
{
isInitialised = true;
}
else
{
Log.e("CritiMon Initialisation", "Incorrect App ID was detected. Please check that you have entered the correct app ID. The app ID can be found on the web pages");
}
}
以下はisAppIdCorrect
機能です
private static void isAppIdCorrect(String appID)
{
new Thread(new Runnable() {
@Override
public void run() {
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(appContext.getString(R.string.post_url) + "/AccountManagement.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("type", "checkAppId"));
nameValuePairs.add(new BasicNameValuePair("appID", CritiMon.appID));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte)current);
}
Log.d("Http Response", new String(baf.toByteArray()));
String httpResponse = new String(baf.toByteArray());
if (httpResponse.equals("200 OK"))
{
appIdValid = true;
}
else
{
appIdValid = false;
}
}
catch (ClientProtocolException ex)
{
Log.e("ClientProtocolException", ex.toString());
}
catch (IOException ex)
{
Log.e("IOException", ex.toString());
}
appIdCheckComplete = true;
}
}).start();
}
したがって、上記のコードでは、isAppIdCorrect
関数は期待どおりに返さ200 OK
れますが、その関数はスレッド内にあるため、スレッドが完了する前にすぐに if ステートメントに移動するため、if ステートメントは false であり、したがって初期化が失敗したと言います。
変数を確認できるように、スレッドが完了するのを待つにはどうすればよいですか。
ご協力いただきありがとうございます。