我正在调用一个线程,该线程将GCM ID返回到名为gcmRegID
的公共变量中问题是线程只在函数结束后被调用
我想知道是否有一种方法可以在函数中间获取gcmRegID的值
我将通过代码解释更多
我想在CheckGCMID中获取gcmRegID的值,但我得到的是“”
String gcmRegID = "";
public void onClick(View view) {
String CheckGCMID;
GetGCM();
CheckGCMID = gcmRegID; // <-- This is always return empty string
}
private void GetGCM() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
GCMHelper gcmRegistrationHelper = new GCMHelper(
getApplicationContext());
gcmRegID = gcmRegistrationHelper.GCMRegister("123456");
// gcmRegID value is "KHDKJDIUHDHDKDK"
} catch (Exception bug) {
bug.printStackTrace();
}
}
});
thread.start();
}
答案 0 :(得分:1)
您应该使用Callback来获取您的值异步。
尝试这样的事情:
public void onClick(View view) {
String CheckGCMID;
GetGCM(new MyCallback(){
@Override
public void receivedString(String myString) {
//use your id here
System.out.println(myString);
}
});
}
private interface MyCallback{
public void receivedString(String myString);
}
private void GetGCM(MyCallback callback) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
GCMHelper gcmRegistrationHelper = new GCMHelper (getApplicationContext());
String gcmRegID = gcmRegistrationHelper.GCMRegister("123456");
callback.receivedString(gcmRegID);
} catch (Exception bug) {
bug.printStackTrace();
}
}
});
thread.start();
}