我很难将非静态处理程序转换为静态处理程序。 我尝试了各种方法,但每次我最终做一些凌乱的事情。 在提供的代码中,请纠正我如何实现这一目标。我尝试过一个例子,我不得不将大部分变量和函数改为静态函数,这些函数是从处理程序引用的。但我仍然有其他错误。
public class MainActivity extends Activity implements Runnable {
private TextView textView;
boolean connectionToTupleSpace=false;
private TupleSpace ts = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.myText);
textView.setText("it is testing");
findViewById(R.id.login_button).setOnClickListener(buttonLogin);
}
public final Button.OnClickListener buttonLogin = new Button.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(MainActivity.this);
thread.start();
}
};
@Override
public void run() {
Looper.prepare();
try {
ts = new TupleSpace("192.168.1.100",2525,"Orientation");
connectionToTupleSpace = true;
}catch (TupleSpaceException e) {
connectionToTupleSpace = false;
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
private Looper myLooper;
@Override
public void handleMessage(Message msg) {
if(connectionToTupleSpace == true)
{
Toast.makeText(getBaseContext(), " Tuple Space Server is Connected", Toast.LENGTH_SHORT).show();
showTuples();
}
else
{
/*Toast.makeText(getBaseContext(), " No connection to Tuple Space Server", Toast.LENGTH_SHORT).show();*/
showDialog("Connection", "there is no connection");
}
myLooper = Looper.myLooper();
Looper.loop();
myLooper.quit();
}
};
public void showTuples()
{
Tuple template = new Tuple(String.class, Integer.class);
Tuple[] returnTuple = null;
try {
returnTuple = ts.readAll(template);
} catch (TupleSpaceException e) {
e.printStackTrace();
}
int num = returnTuple.length;
if (num == 0)
System.out.print("No tuples in the space");
else
for(int i=0;i<num;i++)
{
System.out.print("\nTotal tuples are" + num+"\nYou found " + returnTuple[i]);
showDialog(returnTuple[i].getField(0).toString(),returnTuple[i].getField(1).toString());
}
}
private void showDialog(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("OK", null);
builder.show();
}
}
答案 0 :(得分:1)
就这样做
private Handler handler = new MyHandler(this);
private static class MyHandler extends Handler {
MainActivity activity;
public MyHandler(MainActivity activity) {
this.activity = activity;
}
@Override
public void handleMessage(Message msg) {
...
activity.showTuples();
...
}
}
要在静态类(MyHandler内)中使用Activity,必须将它像参数一样传递给构造函数。
编辑:添加了带有MainActivity参数的构造函数。