0
下面是代碼,如果點擊按鈕,結果活動應該開始:線程在我的代碼不能正常工作
public class Tab19 extends Activity {
ImageButton button1;
SoundPool mSoundPool;
AssetManager assets;
int catSound;
int countLoadedSound;
Context mContext;
ProgressDialog dialog;
int count = 0;
TextView t;
boolean has_been_clicked = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab19);
count = getIntent().getIntExtra("CountNum", 0);
mContext = this;
mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
assets = getAssets();
catSound = loadSound("catSound.mp3");
button1 = (ImageButton)findViewById(R.id.button2);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
playSound(catSound);
Intent firstIntent = new Intent(Tab19.this, Results.class);
TextView t = (TextView)findViewById(R.id.t);
t.setText("score: " + ++count +"/18");
firstIntent.putExtra("CountNum", count);
has_been_clicked = true;
startActivity(firstIntent);
finish();
}
});
new Thread(
new Runnable() {
public void run() {
while (!has_been_clicked) {
try {
// Thread will sleep for 10 seconds
sleep(10*1000);
} catch (Exception e) {
}
}
Intent i=new Intent(getBaseContext(),Results.class);
i.putExtra("CountNum", count);
startActivity(i);
finish();
return;
}
private void sleep(int i) {
// TODO Auto-generated method stub
}
}
).start(); }
@Override
protected void onDestroy() {
super.onDestroy(); }
protected void playSound(int sound) {
if (sound > 0)
mSoundPool.play(sound, 1, 1, 1, 0, 1);
}
private int loadSound(String fileName) {
AssetFileDescriptor afd = null;
try {
afd = assets.openFd(fileName);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Не могу загрузить файл " + fileName,
Toast.LENGTH_SHORT).show();
return -1;
}
return mSoundPool.load(afd, 1);
} }
如果按鈕沒有被點擊線程應該在10秒內啓動下一個活動,但它不會發生,請幫我找一個錯誤。在此先感謝
將一個'Log.d()'對象在'while'循環之後,並在logcat中查看它是否被觸發。 – nKn
爲什麼你有自己的本地實現sleep(),它什麼都不做?此外,由於您沒有將標誌聲明爲volatile,因此您的線程可能不會實際檢查是否已從另一個線程更新過,也不是其他線程有義務實際向內存提交更新。 –
實現這個方法是正確的,但是你有沒有任何理由不在onClick()監聽器中實現呢?這樣用戶點擊圖像,活動'完成()'並立即啓動另一個。 – nKn