我有一個Android的服務如下:在Android上的線程中運行無限循環時,應用程序崩潰。
public class TestService extends Service {
.
.
. // Variables
.
private Thread ChangeColors;
private final int[] colors = {Color.BLACK, Color.RED, Color.YELLOW, Color.BLUE, Color.GREEN};
@Override
public void onStartCommand(Intent intent, int flags, int startID) {
LinearLayout layout = TestActivity.getLayout(); // Returns the layout from the activity class
changeColors = new Thread() {
int index = 0;
@Override
public void run() {
while(!isInterrupted()) {
try {
layout.setBackgroundColor(colors[index]); // Set the background to the Color at the index'th position in the array.
index ++; // Increment the index count. This will throw ArrayIndexOutOfBoundsException once the index > colors.length
} catch(ArrayIndexOutOfBoundsException exception) {
index = 0; // Then simply set the value of index back to 0 and continue looping.
}
}
}
};
changeColors.start();
return START_STICKY;
}
.
.
Other methods
.
.
@Override
public void onDestroy() {
super.onDestroy();
changeColors.interrupt();
Toast.makeText(this, "Stopped!", Toast.LENGTH_SHORT).show();
}
}
該服務只是獲取android.widget.LinearLayout
實例從Activity
上的按鈕,點擊不斷變化的LinearLayout
的背景色。
這是活動:
public class TestActivity extends Activity {
private static LinearLayout layout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT
));
Button butt = new Button(this);
butt.setText("Start thread!");
button.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
));
layout.addView(butt);
setContentView(layout);
butt.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
butt.setBackgroundColor(Color.BLACK);
startService(getContextBase(), TestService.class);
}
}
);
// I have another button coded here which on clicking calls the stopService() method.
}
public static LinearLayout getLayout() {
return layout;
}
}
程序似乎是相當簡單的。該應用在我的LG-L90
手機上啓動得很好。但只要我點擊butt
按鈕,butt
的顏色就會變爲黑色,並且應用程序會立即崩潰,而不會在Service
中運行循環。
我哪裏錯了?請幫忙。我真的想看看線程如何幫助我們做這些事情,並不斷改變可能有助於我在遊戲開發中的GUI。
在此先感謝。
我認爲你必須在UI線程中進行UI操作。將這部分代碼放在'runOnUiThread'中。 – 2014-11-20 21:00:03
你能爲我寫代碼嗎? M新的android。但是有了Java的經驗。儘管如此,從未編寫過多線程應用程序。 – 2014-11-20 21:02:04