[Android]在Avtivity中注册监听器

阅读更多

package com.example.xmlbroadcast;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView tx1=null;
	private Button bt1=null;
	private Button bt2=null;
	private Button bt3=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt1=(Button)findViewById(R.id.btn);
        bt1.setText("发出广播");
        bt1.setOnClickListener(new bt1listener());
        bt2=(Button)findViewById(R.id.btn2);
        bt2.setText("注册监听器");
        bt2.setOnClickListener(new bt2listener());
        bt3=(Button)findViewById(R.id.btn3);
        bt3.setText("注销监听器");
        bt3.setOnClickListener(new bt3listener());
        tx1=(TextView)findViewById(R.id.txv);
    }

    class bt1listener implements OnClickListener{

		public void onClick(View v) {
			// TODO Auto-generated method stub
			tx1.setText("fuck");
			Intent it1=new Intent();
			it1.setAction(Intent.ACTION_EDIT);
			MainActivity.this.sendBroadcast(it1);
		}
    	
    }

	public	TestReceiver mr1 = new TestReceiver(); //创建监听器对象
    class bt2listener implements OnClickListener{

		public void onClick(View v) {
			IntentFilter if1=new IntentFilter();
			if1.addAction(Intent.ACTION_EDIT);
			MainActivity.this.registerReceiver(mr1,if1);
		}
    	
    }

    class bt3listener implements OnClickListener{

		public void onClick(View v) {
			MainActivity.this.unregisterReceiver(mr1);
		}
    	
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
 这里要注意一点,在注销监听器的时候,一定要保证监听器存在,否则程序会报错!

你可能感兴趣的:(Android,广播,监听器,bbezxcy)