如何启用或禁用BroadCast onReceive()方法中的按钮

时间:2016-04-08 05:13:52

标签: android broadcastreceiver

我有一个按钮,可以像在线离线一样充当网络状态指示器。我的问题是我有一个{em}扩展的WifiStatusReceiverbroadcast receiver。 我想启用或禁用WifiStatusReceiver课程中的按钮。我怎么能这样做?

public class Wifi extends BroadcastReceiver implements ActionBar.TabListener{
ActionBar actionBar;
@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();

    ConnectivityManager connectivityManager =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

    if (activeNetInfo != null
            && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
        Toast.makeText(context, "Wifi Connected!", Toast.LENGTH_SHORT).show();
        actionBar.setCustomView(R.layout.header);
        actionBar.getCustomView().findViewById(R.id.btn_onlinestatus).setBackground(context.getResources().getDrawable(R.drawable.onlinestaticon));
    } else {
        Toast.makeText(context, "Wifi Not Connected!", Toast.LENGTH_SHORT).show();

      actionBar.setCustomView(R.layout.header);
       actionBar.getCustomView().findViewById(R.id.btn_onlinestatus).setBackground(context.getResources().getDrawable(R.drawable.offlinestaticon));
    }
}
  

如果我尝试设置按钮的背景,则抛出一个空指针异常,说明" java.lang.RuntimeException:无法启动接收器com.balaji.example.Operations.Wifi:java.lang.NullPointerException&# 34;

3 个答案:

答案 0 :(得分:0)

我认为你应该在这种情况下使用LocalBroadCast - OnCreate你注册接收者 - 在按钮监听器中,如果您不希望它发生,则取消注册,如果您愿意,可以再次注册 - onPause或onStop(也许)你检查是否注册> unregisterReceiver

答案 1 :(得分:0)

    public class Wifi extends BroadcastReceiver {

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

        ConnectivityManager connectivityManager =
                (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

         Intent broadcastIntent = new Intent();
         broadcastIntent.setAction("EnableDisableAction");
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {        

        Toast.makeText(context, "WifiConnected!",Toast.LENGTH_SHORT).show();
        broadcastIntent.putExtra("enableordisable", true);


        } else {
            Toast.makeText(context, "Wifi Not Connected!", Toast.LENGTH_SHORT).show();
            broadcastIntent.putExtra("enableordisable", false);
        }
        arg0.sendBroadcast(broadcastIntent);
    }

Now in your activity

private IntentFilter intfilt; 
private boolean enableOrDisable=false;
private ActionBar actionBar;
BroadcastReceiver enableDisableBrodcastRecr = new BroadcastReceiver() 
    {

        @Override
        public void onReceive(Context arg0, Intent arg1) {

            enableOrDisable=arg1.getExtras().getBoolean("enableordisable");//enableordisable is Key which is passed inside onReceive method of Wifi

            // For Refreshing The message

        }
    };

onCreate()
{
    intfilt = new IntentFilter();
    intfilt.addAction("EnableDisableAction");
}

onResume()
{
 registerReceiver(enableDisableBrodcastRecr, intfilt);

 if(enableOrDisable==true)

    {
actionBar.setCustomView(R.layout.header);
        actionBar.getCustomView().findViewById(R.id.btn_onlinestatus).setBackground(context.getResources().getDrawable(R.drawable.onlinestaticon));

    }else
    {
actionBar.setCustomView(R.layout.header);
       actionBar.getCustomView().findViewById(R.id.btn_onlinestatus).setBackground(context.getResources().getDrawable(R.drawable.offlinestaticon));
    }

}

onPause()
{
        unregisterReceiver(enableDisableBrodcastRecr);
}

根据您的要求/设计,您也可以在onCreate()-onDestroy()onStart()-onStop()

内注册和取消注册接收者

因此,如果unRegisterReceiver被调用则要小心它将无法监听发送的广播意图

注意:您不应该更新UI线程以外的UI

答案 2 :(得分:0)

    Main Activity

    package com.checkisonline;

    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.app.Activity;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.graphics.Color;
    import android.view.Menu;
    import android.widget.Button;

    public class MainActivity extends Activity {

        Button wifiState;
        private IntentFilter intfilt; 
        private boolean enableOrDisable=false;

        BroadcastReceiver enableDisableBrodcastRecr = new BroadcastReceiver() 
        {

            @Override
            public void onReceive(Context arg0, Intent arg1) {


                enableOrDisable=arg1.getExtras().getBoolean("enableordisable");//enableordisable is Key which is passed inside onReceive method of Wifi

                handler.sendEmptyMessage(0);

            }
        };

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

            intfilt = new IntentFilter();
            intfilt.addAction("EnableDisableAction");

            registerReceiver(enableDisableBrodcastRecr, intfilt);

            wifiState=(Button)findViewById(R.id.state);

        }

        @Override
        protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();


             if(checkWifiState()==true)
                {

                 wifiState.setText("Wifi-ON");
                 wifiState.setTextColor(Color.GREEN);
                }else
                {

                    wifiState.setText("Wifi-OFF");
                    wifiState.setTextColor(Color.RED);
                }
        }

        @Override
        protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();

        }

        @Override
        protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();

            unregisterReceiver(enableDisableBrodcastRecr);
        }

        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {

                if(enableOrDisable==true)
                {

                 wifiState.setText("Wifi-ON");
                 wifiState.setTextColor(Color.GREEN);
                }else
                {

                    wifiState.setText("Wifi-OFF");
                    wifiState.setTextColor(Color.RED);
                }

            }
    };

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }


        public boolean checkWifiState()
        {
            boolean wifistate;
            ConnectivityManager connectivityManager =
                    (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();


            if (activeNetInfo != null
                    && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {        
                wifistate=true;

            } else {
                wifistate=false;
            }

            return wifistate;
        }



    }

    Wifi Receiver 

    package com.checkisonline;

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



         public class WifiReceiver extends BroadcastReceiver {

                @Override
                public void onReceive(Context context, Intent intent) {

                    ConnectivityManager connectivityManager =
                            (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();

                     Intent broadcastIntent = new Intent();
                     broadcastIntent.setAction("EnableDisableAction");
                    if (activeNetInfo != null
                            && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) { 

                        broadcastIntent.putExtra("enableordisable", true);

                    } else {

                        broadcastIntent.putExtra("enableordisable", false);

                    }
                    context.sendBroadcast(broadcastIntent);
                }
         }

    activity_main.xml

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <Button
                android:id="@+id/state"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="176dp"
                android:textSize="20dp"

                 />

        </RelativeLayout>

    Manifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.checkisonline"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.checkisonline.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

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

            <receiver android:name="com.checkisonline.WifiReceiver" android:enabled="true">
            <intent-filter>
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>


        </application>

    </manifest>

Now as you required use ActionBar object wherever I used Button.
Enjoy....