[英]Problems with the Android Broadcast Receiver
I found this Question multiple times but none of the Solutions seemed to work.我多次发现这个问题,但似乎没有一个解决方案有效。
I have the following in the manifest:我在清单中有以下内容:
<receiver android:name=".noactivity.Airplane">
<intent-filter>
<action android:name="android.intent.action.AIRPLANE_MODE_CHANGED"/>
</intent-filter>
</receiver>
And the following class:以及以下课程:
public class Airplane extends BroadcastReceiver {
public Airplane(){
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d("AirplaneMode", "Service state changed");
Toast.makeText(context,"Airplane mode changed",Toast.LENGTH_LONG).show();
}}
But if I change the Airplane mode nothing happens.但是,如果我更改飞行模式,则什么也不会发生。 To be sure I also added:
可以肯定的是,我还添加了:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(new Airplane(), new IntentFilter("android.intent.action.AIRPLANE_MODE_CHANGED"));
}}
What also didn't work.什么也没有奏效。 Do any of you know what I'm doing wrong?
你们中有人知道我做错了什么吗?
I use this successfully without adding the receiver in manifest.我成功地使用了它,而没有在清单中添加接收器。 In you activity add this:
在您的活动中添加:
@Override
protected void onResume() {
//register receiver for air plane mode states
IntentFilter airPlaneModeFilter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(airPlaneModeReceiver, airPlaneModeFilter);
super.onResume();
}
private BroadcastReceiver airPlaneModeReceiver = new BroadcastReceiver() {@Override
public void onReceive(Context context, Intent intent) {
boolean airPlaneModeEnabled = intent.getBooleanExtra("state", false);
if (airPlaneModeEnabled) {
} else {
}
}
};
@Override
protected void onPause() {
if (airPlaneModeReceiver != null) unregisterReceiver(airPlaneModeReceiver);
super.onPause();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.