Network Data Packet connectivity intent

Posted by Rakesh on Stack Overflow See other posts from Stack Overflow or by Rakesh
Published on 2012-06-24T08:21:58Z Indexed on 2012/06/24 9:15 UTC
Read the original article Hit count: 338

I am writing an Android application which can enable and disable the Network Data packet connection. I am also using one broadcast receiver to check the Network Data packet connection. I have registered broadcast receiver and provided required permission in Manifest file. But when I run this application it changes the connection state and after that it crashes. But when I don't include this broadcast receiver it works fine. I am not able to see any kind of log which can provide some clue.

Here is my code for broadcast receiver.

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

    <uses-sdk android:minSdkVersion="10" />
    <!-- Permissions -->
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SimpleWidgetExampleActivity"
            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=".ExampleAppWidgetProvider"
            android:label="Widget ErrorBuster" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget1_info" />
        </receiver>
        -->
        <receiver android:name=".ConnectivityReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

My Broadcast receiver class is as following.

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


public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        NetworkInfo info = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        if(info.getType() == ConnectivityManager.TYPE_MOBILE){ 
            if(info.isConnectedOrConnecting()){
                Log.e("RK","Mobile data is connected");
            }else{
                Log.e("RK","Mobile data is disconnected");
            }
        }
    }

}

my Main activity file.

package com.rakesh.simplewidget;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class SimpleWidgetExampleActivity extends Activity {
    private Button btNetworkSetting;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btNetworkSetting = (Button)findViewById(R.id.btNetworkSetting);
        if(checkConnectivityState(getApplicationContext())){
            btNetworkSetting.setBackgroundColor(Color.GREEN);
        }else{
            btNetworkSetting.setBackgroundColor(Color.GRAY);
        }
    }

    public void openNetworkSetting(View view){

        Method dataConnSwitchmethod;
        Class telephonyManagerClass;
        Object ITelephonyStub;
        Class ITelephonyClass;
        Context context = view.getContext();
        boolean enabled = !checkConnectivityState(context);
        final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);


        try{
            final Class conmanClass = Class.forName(conman.getClass().getName());
            final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
            iConnectivityManagerField.setAccessible(true);
            final Object iConnectivityManager = iConnectivityManagerField.get(conman);
            final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
            final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
            setMobileDataEnabledMethod.setAccessible(true);

            setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);

            if(enabled){
                Toast.makeText(view.getContext(), "Enabled Network Data", Toast.LENGTH_LONG).show();
                view.setBackgroundColor(Color.GREEN);
            }
            else{
                Toast.makeText(view.getContext(), "Disabled Network Data", Toast.LENGTH_LONG).show();
                view.setBackgroundColor(Color.LTGRAY);
            }
        }catch(Exception e){
            Log.e("Error", "some error");
            Toast.makeText(view.getContext(), "It didn't work", Toast.LENGTH_LONG).show();
        }
    }

    private boolean checkConnectivityState(Context context){
        final TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        ConnectivityManager af ;
        return telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED;

    }
}

Log file:

java.lang.RuntimeException: Unable to instantiate receiver com.rakesh.simplewidget.ConnectivityReceiver: java.lang.ClassNotFoundException: com.rakesh.simplewidget.ConnectivityReceiver in loader dalvik.system.PathClassLoader[/data/app/com.rakesh.simplewidget-2.apk]
E/AndroidRuntime(26094):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:1777)
E/AndroidRuntime(26094):    at android.app.ActivityThread.access$2400(ActivityThread.java:117)
E/AndroidRuntime(26094):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
E/AndroidRuntime(26094):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(26094):    at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime(26094):    at android.app.ActivityThread.main(ActivityThread.java:3691)
E/AndroidRuntime(26094):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(26094):    at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(26094):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
E/AndroidRuntime(26094):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
E/AndroidRuntime(26094):    at dalvik.system.NativeStart.main(Native Method)

It seems Android is not able to recognize file Broadcast Receiver class. Any idea why I am getting this error?

PS: Some information about Android environment and platform. - Android API 10. - Running on Samsung Galaxy II which has android 2.3.6

Edit:

my broadcast receiver file ConnectivityReceiver.java was present in default package and it was not being recognized by Android. Android was looking for this file in current package i.e com.rakesh.simplewidget; I just moved connectivityReciever.java file to com.rakesh.simplewidget package and problem was solved.

© Stack Overflow or respective owner

Related posts about android

Related posts about broadcastreceiver