自定义广播和系统广播不一样的是,action是自定义的自己随便定义,在清单文件中体现,这个在现实中用的很少,大部分都是接受系统广播。
代码示例
app1:发送广播(专门发广播)
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送自定义广播"
android:onClick="click"
/>
</RelativeLayout>
MainActivity.java
package com.ldw.selfbroadcast;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v){
//发送自定义广播
Intent intent = new Intent();
//广播中的action是自定义的
intent.setAction("com.ldw.self");
sendBroadcast(intent);
}
}
app2:接受自定义广播(接受广播)
清单文件需要添加的配置
<receiver android:name="com.ldw.receiveself.selfReceiver">
<intent-filter>
<action android:name="com.ldw.self"/>
</intent-filter>
</receiver>
selfReceiver.java
package com.ldw.receiveself;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class selfReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("自定义广播");
}
}
MainActivity.java
package com.ldw.receiveself;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@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;
}
}
本文介绍了Android中自定义广播的应用方式,包括如何通过MainActivity发送自定义广播,并在另一个应用中接收这些广播。文中提供了完整的代码示例,展示了如何定义自定义Action、发送广播以及配置接收器。
2722

被折叠的 条评论
为什么被折叠?



