布局文件
点击按钮发送广播
activity
在Activity中监听按钮事件并创建意图对象,通过sendBroadcast将意图对象发送出去
package xidian.dy.com.chujia;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;public class MainActivity extends AppCompatActivity { SharedPreferences sp; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); sp = getSharedPreferences("hate", Context.MODE_PRIVATE); Button button = (Button) findViewById(R.id.sure); if(button != null) button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction("com.dy.xd.test"); sendBroadcast(intent); } }); }}
广播接收者
package xidian.dy.com.chujia;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;/** * Created by dy on 2016/7/12. */public class Custom extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Toast.makeText(context, "我的广播" +action, Toast.LENGTH_SHORT).show(); }}
清单文件
在清单文件中需要我们在创建意图对象时设置的action