发送自定义广播: 1.定义Broadcast接收器
public class mBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO 自动生成的方法存根 Toast.makeText(context, "mBroadcastReceiver", Toast.LENGTH_SHORT).show(); } }2.然后在 AndroidManifest.xml 中对这个广播接收器进行注册:
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <receiver android:name=".mBroadcastReceiver" android:exported="false" > <intent-filter> <action android:name="com.example.broadcastreceiverdemo.MY_BROADCAST" /> </intent-filter> </receiver> <activity android:name="com.example.broadcastreceiverdemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>3.MainActivity中,button 发送广播
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button=(Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent("com.example.broadcastreceiverdemo.MY_BROADCAST"); sendBroadcast(intent); } }); }