我有一个 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
的背景颜色。
这是 Activity :
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,这可能会帮助我有一天进行游戏开发。
提前致谢。
最佳答案
您应该使用 runOnUiThread
进行 UI 操作。
public class MyService extends Service {
Handler handler;
public MyService() {
}
@Override
public void onCreate() {
super.onCreate();
handler = new Handler();
}
private void runOnUiThread(Runnable runnable) {
handler.post(runnable);
}
...
}
并确保您导入了 android.os.Handler
,现在调用 runOnUiThread
方法。
关于android - 在 Android 上,应用程序在线程中运行无限循环时崩溃。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049426/