gpt4 book ai didi

android - 从android中的 Activity 启动广播接收器

转载 作者:IT老高 更新时间:2023-10-28 23:30:39 25 4
gpt4 key购买 nike

我想从一个 Activity 中启动一个广播接收器。我有一个 Second.java 文件,它扩展了一个广播接收器和一个 Main.java 文件,我必须从中启动广播接收器。我也尝试在 Main.java 中按如下方式执行所有操作,但不知道如何在 list 文件中定义...

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 调用广播接收器?谁能让我知道我在哪里做错了?谢谢!

最佳答案

使用这个为什么发送自定义广播:

定义一个 Action 名称:

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>

注册接收者:

IntentFilter intentFilter = new IntentFilter(BROADCAST);
registerReceiver( myReceiver , intentFilter);

从您的 Activity 发送广播:

Intent intent = new Intent(BROADCAST);  
Bundle extras = new Bundle();
extras.putString("send_data", "test");
intent.putExtras(extras);
sendBroadcast(intent);

你的广播接收器:

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

关于android - 从android中的 Activity 启动广播接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9972769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com