gpt4 book ai didi

android - 单击按钮时触发 BroadcastReceiver

转载 作者:行者123 更新时间:2023-11-29 18:00:46 32 4
gpt4 key购买 nike

当我点击 main.xml 上的按钮时,我正在尝试接收 BroadcastReceiver

                       **mainfest.xml**
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".boardCast">

<intent-filter>
<action android:name="borad.cast"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>

</application>

上面的manifest file receiver注册我们自己的action like android.action="broad.cast"

                             **mainActivty.java**
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button samll = (Button)findViewById(R.id.button1);
samll.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
Intent ii = new Intent(getApplicationContext(),boardCast.class);
PendingIntent pp = PendingIntent.getBroadcast(getApplicationContext(), 0, ii, 0);

}
});
}

在 Activty 类上可以包含按钮,当我单击该按钮时 BroadcastReceiver 应该触发 板播.java

     @Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals("borad.cast")){
Toast.makeText(context, "sample", Toast.LENGTH_LONG).show();
}
}

最佳答案

摆脱挂起的 Intent 并这样做:

在按钮的点击事件调用的 onclick 上:

 public void onClick(View v) {
// TODO Auto-generated method stub
broadcastMsg("borad.cast");

}
});

//这里是函数定义:

public void broadcastMsg(String intentName) {
final Intent intent = new Intent(intentName);
sendBroadcast(intent);
}

关于android - 单击按钮时触发 BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16238297/

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