为什么我的BroadCast接收器不起作用? [英] Why is my BroadCast Receiver not working?

查看:118
本文介绍了为什么我的BroadCast接收器不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在了解BroadCast接收器。我尝试使用以下代码实现的是,当我切换到飞行模式时,无论是否开启应用程序,我都希望看到一个敬酒。我在做什么/做错了什么?请帮忙。谢谢

I am learning about BroadCast Receivers. What I am trying to achieve with the following piece of code is, I would like to see a toast when I switch to airplane mode, where the app is on or not. What am I not doing / Doing wrong? Please Help. Thanks

ConnectivityChangedReceiver.java类

ConnectivityChangedReceiver.java class

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

public class ConnectivityChangedReceiver extends BroadcastReceiver {

@Override
public void onReceive( Context context, Intent intent )
{
    Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();

}
}

AndroidManifest.xml

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <receiver android:name=".ConnectivityChangedReceiver">
        <intent-filter>
            <action android:name="android.intent.action.AIRPLANE_MODE">
            </action>
        </intent-filter>

    </receiver>

</application>

MainActivity.java`

MainActivity.java`

 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.content.Intent;


 import java.util.ArrayList;

 public class MainActivity extends AppCompatActivity {

private TextView switchStatus;
private Switch mySwitch;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 }
 }


推荐答案

所以我刚刚找到上述问题的解决方案。
我更改了

So I just found the solution to my problem above. I changed

<receiver android:name=".ConnectivityChangedReceiver">

<receiver android:name="ConnectivityChangedReceiver">

(名字开头没有。。希望它对陷入困境的人有所帮助!

(Without the '.' at the beginning of name. Hope it helps a stranded one!

这篇关于为什么我的BroadCast接收器不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆