M.M*_*agh 2 java multithreading android
我想在Android中更改UI.
我的主类创建第二个类然后第二个类调用主类的主类class.method的方法应该更新UI但程序在运行时崩溃.
我该怎么办?
我的主要课程:
public class FileObserverActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("new world");
MyFileObserver myFileObserver = new MyFileObserver("/sdcard/", this);
myFileObserver.startWatching();
}
String mySTR = "";
TextView tv ;
public void event(String absolutePath,String path,int event)
{
mySTR = absolutePath+path+"\t"+event;
tv.setText(mySTR); // program crash here!
}
}
Run Code Online (Sandbox Code Playgroud)
和我的第二堂课:
public class MyFileObserver extends FileObserver
{
public String absolutePath;
FileObserverActivity fileobserveractivity;
public MyFileObserver(String path,FileObserverActivity foa)
{
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
fileobserveractivity = foa;
}
@Override
public void onEvent(int event, String path)
{
if (path == null)
{
return;
}
else if(event!=0)
{
fileobserveractivity.event(absolutePath, path, event);
}
else
{
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 8
您不能从主线程以外的线程调用UI方法.您应该使用Activity#runOnUiThread()方法.
public class FileObserverActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("new world");
MyFileObserver myFileObserver = new MyFileObserver("/sdcard/", this);
myFileObserver.startWatching();
}
String mySTR = "";
TextView tv ;
public void event(String absolutePath,String path,int event)
{
runOnUiThread(action);
}
private Runnable action = new Runnable() {
@Override
public void run() {
mySTR = absolutePath+path+"\t"+event;
tv.setText(mySTR);
}
};
}
public class MyFileObserver extends FileObserver
{
public String absolutePath;
FileObserverActivity fileobserveractivity;
public MyFileObserver(String path,FileObserverActivity foa)
{
super(path, FileObserver.ALL_EVENTS);
absolutePath = path;
fileobserveractivity = foa;
}
@Override
public void onEvent(int event, String path)
{
if (path == null)
{
return;
}
else if(event!=0)
{
fileobserveractivity.event(absolutePath, path, event);
}
else
{
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8936 次 |
| 最近记录: |