76 Android BroadcastReceiver简单使用

activity_main.xml (布局文件中添加一个按钮)



    


MyBroadcastReceiver  extends BroadcastReceiver

MyBroadcastReceiver.java

package com.example.android_broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyBroadcastReceiver  extends BroadcastReceiver {

	
	public MyBroadcastReceiver() {
		
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onReceive(Context arg0, Intent arg1) {
		// TODO Auto-generated method stub
		String name=arg1.getStringExtra("name");
		Toast.makeText(arg0, "Hello World----"+name, 1).show();
	}

}


MainActivity.java

package com.example.android_broadcast;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
	private Button button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button=(Button)findViewById(R.id.button1);
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent=new Intent(MainActivity.this, MyBroadcastReceiver.class);
				intent.putExtra("name", "Tom");
				sendBroadcast(intent);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
76 Android BroadcastReceiver简单使用_第1张图片






你可能感兴趣的:(Android)