【发布时间】:2014-11-20 20:57:01
【问题描述】:
我有一个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();
}
}
此服务只需单击按钮即可从Activity 获取android.widget.LinearLayout 实例,并不断更改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中。 -
你能帮我写代码吗?安卓新手。但是有Java经验。不过从未编写过多线程应用程序。
标签: android multithreading crash