我想从一项活动中启动广播接收器。我有一个Second.java文件,它扩展了广播接收器和Main.java文件,我必须从中启动广播接收器。 我也尝试在Main.java中执行如下操作,但不知道如何在清单文件中定义...
public class Main extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String rec_data = "Nothing Received";
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if( intent.getStringExtra("send_data")!=null)
rec_data = intent.getStringExtra("send_data");
Log.d("Received Msg : ",rec_data);
}
};
}
protected void onResume() {
IntentFilter intentFilter = new IntentFilter();
//intentFilter.addDataType(String);
registerReceiver(myReceiver, intentFilter);
super.onResume();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
this.unregisterReceiver(this.myReceiver);
}
}
如果我不能像上面那样在一个班级做所有事情,我如何从Main.java调用广播接收器?任何人都可以让我知道我做错了吗?谢谢!
答案 0 :(得分:28)
使用此原因发送自定义广播:
定义一个动作名称:
public static final String BROADCAST = "PACKAGE_NAME.android.action.broadcast";
AndroidManifest.xml注册接收者:
<receiver android:name=".myReceiver" >
<intent-filter >
<action android:name="PACKAGE_NAME.android.action.broadcast"/>
</intent-filter>
</receiver>
Register Reciver:
IntentFilter intentFilter = new IntentFilter(BROADCAST);
registerReceiver( myReceiver , intentFilter);
从您的活动发送广播:
Intent intent = new Intent(BROADCAST);
Bundle extras = new Bundle();
extras.putString("send_data", "test");
intent.putExtras(extras);
sendBroadcast(intent);
你的BroadcastReceiver:
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle extras = intent.getExtras();
if (extras != null){
{
rec_data = extras.getString("send_data");
Log.d("Received Msg : ",rec_data);
}
}
};
有关自定义广播的详细信息,请参阅Custom Intents and Broadcasting with Receivers
答案 1 :(得分:2)
在这里查看本教程,您将获得有关广播的所有帮助,包括如何从活动开始服务,反之亦然
答案 2 :(得分:0)
为此您必须广播接收者的意图,请参阅以下代码: -
Intent intent=new Intent();
getApplicationContext().sendBroadcast(intent);
您可以设置Intent的操作和其他属性,并可以使用Application上下文进行广播,无论您在此处设置的Intent操作是否必须在AndroidManifest.xml中使用receiver标记进行定义。
答案 3 :(得分:0)