Android接收和发送消息

时间:2013-07-23 08:51:44

标签: android

我有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)的代码如何?

1 个答案:

答案 0 :(得分: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);  
}

ActivityTwo

@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" >

<强> EDIT2:

你也可以在普通的课堂上使用上面的代码或类似的东西:

public class ordinary{
    private Handler handler = null;  

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

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

编辑结束