0

我有1个活动和1个普通类,其中一个活动接收消息,普通类发送消息。如何实现它:

在 ActivityOne.class

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    public mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 10:
                   Toast("Get message 10");
                   break;
                case 1:
                   Toast("Get message 1");
                   break;
            }
        }
    };
}

public void Toast(String text) {
    Toast.makeText(ActivityOne.this, text, Toast.LENGTH_SHORT).show();
}

在 Ordinary.class

如何编码 sendEmptyMessage(1) ?

4

1 回答 1

1

你可以使用它

编辑:

public class TestApplication extends Application{

private Handler handler = null;  

    public void setHandler(Handler handler) { this.handler = handler; }  
    public Handler getHandler() { return handler; }  
} 

然后在 ActivityOne

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 10:
                   Toast("Get message 10");
                   break;
                case 1:
                   Toast("Get message 1");
                   break;
            }
        }
    };
    TestApplication mAPP = (TestApplication) getApplication(); 
    mAPP.setHandler(mHandler);  
}

活动二

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity_two);
    TestApplication mAPP = (TestApplication) getApplication(); 
    mAPP.getHandler().sendEmptyMessage(1);

}

并且您必须修复 AndroidManifest.xml 添加android:name=".TestApplication"

<application
    android:allowBackup="true"
    android:name=".TestApplication"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

编辑2:

您也可以在普通类中使用上面的代码或类似的东西:

public class ordinary{
    private Handler handler = null;  

    public ordinary(Handler handler) { this.handler = handler; }  
    public void doSomeThing(){
        handler .sendEmptyMessage(1);
    }
}

在活动一中:

ordinary clazz = new ordinary(mHandler);
clazz.doSomeThing();

编辑结束

于 2013-07-23T09:01:06.543 回答