List JmDNS Services in Android App-Collection of common programming errors


  • user268397

    I’m trying to list some JmDNS services that I discover in my Android app and whenever I call this method my app crashes in the emulator? I tried commenting out blocks of code and code inside methods and it still crashes on the emulator. Anybody have any ideas?

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    
    import javax.jmdns.JmDNS;
    import javax.jmdns.ServiceInfo;
    
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo.State;
    import android.net.wifi.WifiInfo;
    import android.net.wifi.WifiManager;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;
    
    
    /**
     * The main activity, which list the available services in the local network.
     * 
     */
    public class ConnectActivity extends Activity {
    
    private final static String LOG_TAG = ConnectActivity.class.getSimpleName();
    
    // ===================View Models===================
    // The view model of the service info list
    private List serviceInfoList = new ArrayList();
    
    private ServiceServer server = null;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.connect);
    
        this.initViewModels();
        this.initEventHandlers();
    
        this.initMockData();
    
        if (!checkWifiStatus()) {
            // this.showToast("No wifi network!");
        }
    
        server = new ServiceServer("Whooznear");
        int startedPort = server.start();
        Log.i(LOG_TAG, "Started at " + startedPort);
    
    
        ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
    
        // This schedule a runnable task every second
        scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
          public void run() {
            //Put Thread Code Here
            //refreshServices();
          }
        }, 0, 1, TimeUnit.SECONDS);
    
    
    }
    
    private void refreshServices() {
        new Thread(new Runnable() {
            public void run() {
                Log.i(LOG_TAG, "refresh services...");
    
                testUpdateService();
    
                JmDNS registry = null;
                try {
                    registry = JmDNS.create();
    
                    List enabledServices = LocalEnvironment
                            .getEnabledServices(ConnectActivity.this);
                    for (String serviceName : enabledServices) {
                        String serviceType = LocalEnvironment
                                .getServiceTypeByTitle(serviceName);
                        Log.i(LOG_TAG, "Register service..." + serviceType);
    
                        String text = "Test service";
                        Map properties = new HashMap();
                        properties.put("srvname", text.getBytes());
                        ServiceInfo service = ServiceInfo.create(serviceType,
                                "apache-someuniqueid", 80, 0, 0, true,
                                properties);
    
                        registry.registerService(service);
                        Log.i(LOG_TAG, "List service..." + service.getType());
                        final ServiceInfo[] services = registry.list(service
                                .getType());
                        Log.i(LOG_TAG, services.length + " services ("
                                + serviceType + ") is found.");
                        ConnectActivity.this.runOnUiThread(new Runnable() {
                            public void run() {
                                for (ServiceInfo service : services) {
                                    serviceInfoList
                                            .add(new ServiceInfoViewModel(service));
                                }
                                notifyServiceListChanged();
                            }
                        });
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    Log.e(LOG_TAG, ex.toString());
                }
            }
        }).start();
    }
    
    private void onRefreshButtonClicked(View source) {
        this.showToast("Clicked " + ((Button) source).getText());
        this.refreshServices();
    }
    
    /*private void onSettingsButtonClicked(View source) {
        Intent intent = new Intent();
        intent.setClass(this, SettingsActivity.class);
        this.startActivityForResult(intent, RESULT_OK);
    }*/
    
    private void onServiceListItemSelected(AdapterView arg0, View arg1,
            int arg2, long arg3) {
        ServiceInfoViewModel selectedService = serviceInfoList.get(arg2);
        Log.i(LOG_TAG, "Selected service at " + selectedService.getServiceIp());
        Intent intent = new Intent();
        intent.putExtra("ServiceName", selectedService.getServiceName());
        intent.putExtra("ServiceAddress", selectedService.getServiceIp());
        intent.setClass(this, ProfileActivity.class);
        this.startActivityForResult(intent, RESULT_OK);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        switch (resultCode) {
        case RESULT_OK:
            break;
        default:
            break;
        }
    }
    
    private void initViewModels() {
        ListView servicesListView = (ListView) this
                .findViewById(R.id.servicesListView);
        ListAdapter servicesListAdapter = new SimpleAdapter(this,
                serviceInfoList, android.R.layout.simple_list_item_2,
                new String[] { "serviceName", "serviceDesc" }, new int[] {
                        android.R.id.text1, android.R.id.text2 });
        servicesListView.setAdapter(servicesListAdapter);
    }
    
    /**
     * Initialize the event handlers
     */
    private void initEventHandlers() {
        // Service List View
        ListView servicesListView = (ListView) this
                .findViewById(R.id.servicesListView);
        servicesListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView arg0, View arg1,
                            int arg2, long arg3) {
                        onServiceListItemSelected(arg0, arg1, arg2, arg3);
                    }
                });
    
        // Refresh Button
        /*Button refreshButton = (Button) this
                .findViewById(R.id.refreshServiceButton);
        refreshButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View source) {
                onRefreshButtonClicked(source);
            }
        });*/
    
        // Settings Button
        /*Button settingsButton = (Button) this
                .findViewById(R.id.appSettingsButton);
        settingsButton.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View source) {
                onSettingsButtonClicked(source);
            }
        });*/
    }
    
    private void initMockData() {
    }
    
    private boolean checkWifiStatus() {
        try {
            ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // Network
            State wifiState = conMan.getNetworkInfo(
                    ConnectivityManager.TYPE_WIFI).getState();
    
            WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            Log.i(LOG_TAG, "IP Address:" + info.getIpAddress());
            LocalEnvironment.LocalIPAddress = info.getIpAddress();
            LocalEnvironment.LocalIdentity = info.getMacAddress();
    
            return wifiState == State.CONNECTED;
        } catch (Exception ex) {
            Log.e(this.getClass().getName(), "Check Wifi Status Failed!", ex);
            this.showToast(ex.toString());
            return false;
        }
    
    }
    
    private void notifyServiceListChanged() {
        ListView servicesListView = (ListView) this
                .findViewById(R.id.servicesListView);
        ((SimpleAdapter) servicesListView.getAdapter()).notifyDataSetChanged();
    }
    
    private void testUpdateService() {
        String text = "Test hypothetical web server";
        Map properties = new HashMap();
        properties.put("srvname", text.getBytes());
        ServiceInfo service = ServiceInfo.create("_html._tcp.local.",
                "apache-someuniqueid", 80, 0, 0, true, properties);
        JmDNS registry = null;
        Exception occuredEx = null;
        int serviceCount = 0;
        try {
            registry = JmDNS.create();
            registry.registerService(service);
    
            ServiceInfo[] services = registry.list(service.getType());
    
            serviceCount = services.length;
            Log.d(LOG_TAG, serviceCount + " services found");
        } catch (IOException ex) {
            this.showToast(ex.toString());
            occuredEx = ex;
        } finally {
            if (registry != null) {
                try {
                    registry.close();
                } catch (IOException ex) {
                    this.showToast(ex.toString());
                    occuredEx = ex;
                }
            }
        }
    }
    
    private void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }
    
    private void showToast(int id) {
        ListView servicesListView = (ListView) this
                .findViewById(R.id.servicesListView);
    
        Toast.makeText(this, servicesListView.getItemAtPosition(id).toString(),
                Toast.LENGTH_SHORT).show();
    }
    }
    

    This is the code I’m using to call the method above:

    Intent myIntent = new Intent(ProfileActivity.this, ConnectActivity.class);
    ProfileActivity.this.startActivity(myIntent);
    

    Here is the stack trace:

    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532): Check Wifi Status Failed!
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532): java.lang.SecurityException: ConnectivityService: Neither user 10036 nor current process has android.permission.ACCESS_NETWORK_STATE.
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.os.Parcel.readException(Parcel.java:1321)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.os.Parcel.readException(Parcel.java:1275)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.net.IConnectivityManager$Stub$Proxy.getNetworkInfo(IConnectivityManager.java:469)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.net.ConnectivityManager.getNetworkInfo(ConnectivityManager.java:264)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at com.whooznear.android.ConnectActivity.checkWifiStatus(ConnectActivity.java:214)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at com.whooznear.android.ConnectActivity.onCreate(ConnectActivity.java:60)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.app.Activity.performCreate(Activity.java:4397)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.app.ActivityThread.access$500(ActivityThread.java:122)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.os.Handler.dispatchMessage(Handler.java:99)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.os.Looper.loop(Looper.java:132)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at android.app.ActivityThread.main(ActivityThread.java:4123)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at java.lang.reflect.Method.invokeNative(Native Method)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at java.lang.reflect.Method.invoke(Method.java:491)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
    01-09 23:42:39.951: E/com.whooznear.android.ConnectActivity(1532):  at dalvik.system.NativeStart.main(Native Method)
    01-09 23:42:39.991: I/ServiceServer(1532): java.net.SocketException: Permission denied
    01-09 23:42:40.032: I/ConnectActivity(1532): Started at -1
    01-09 23:42:40.041: W/dalvikvm(1532): threadid=9: thread exiting with uncaught exception (group=0x40    014760)
    01-09 23:42:40.071: E/AndroidRuntime(1532): FATAL EXCEPTION: Thread-12
    01-09 23:42:40.071: E/AndroidRuntime(1532): java.lang.NullPointerException
    01-09 23:42:40.071: E/AndroidRuntime(1532):     at com.whooznear.android.ServiceServer.serverThreadProc(ServiceServer.java:61)
    01-09 23:42:40.071: E/AndroidRuntime(1532):     at com.whooznear.android.ServiceServer.access$0(ServiceServer.java:57)
    01-09 23:42:40.071: E/AndroidRuntime(1532):     at com.whooznear.android.ServiceServer$1.run(ServiceServer.java:52)
    01-09 23:42:40.693: D/dalvikvm(1532): GC_CONCURRENT freed 416K, 7% free 7200K/7687K, paused 6ms+27ms
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532): Check Wifi Status Failed!
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532): java.lang.SecurityException: ConnectivityService: Neither user 10036 nor current process has android.permission.ACCESS_NETWORK_STATE.
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.os.Parcel.readException(Parcel.java:1321)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.os.Parcel.readException(Parcel.java:1275)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.net.IConnectivityManager$Stub$Proxy.getNetworkInfo(IConnectivityManager.java:469)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.net.ConnectivityManager.getNetworkInfo(ConnectivityManager.java:264)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at com.whooznear.android.ConnectActivity.checkWifiStatus(ConnectActivity.java:214)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at com.whooznear.android.ConnectActivity.onCreate(ConnectActivity.java:60)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.app.Activity.performCreate(Activity.java:4397)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.app.ActivityThread.access$500(ActivityThread.java:122)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.os.Handler.dispatchMessage(Handler.java:99)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.os.Looper.loop(Looper.java:132)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at android.app.ActivityThread.main(ActivityThread.java:4123)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at java.lang.reflect.Method.invokeNative(Native Method)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at java.lang.reflect.Method.invoke(Method.java:491)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
    01-09 23:42:41.041: E/com.whooznear.android.ConnectActivity(1532):  at dalvik.system.NativeStart.main(Native Method)
    01-09 23:42:41.151: I/ServiceServer(1532): java.net.SocketException: Permission denied
    01-09 23:44:09.541: I/ActivityThread(1575): Pub com.whooznear.android: com.whooznear.android.ProfileProvider
    01-09 23:44:10.054: D/dalvikvm(1575): GC_FOR_ALLOC freed 40K, 4% free 6337K/6595K, paused 247ms
    01-09 23:44:10.112: I/dalvikvm-heap(1575): Grow heap (frag case) to 6.805MB for 588816-byte allocation
    01-09 23:44:10.422: D/dalvikvm(1575): GC_FOR_ALLOC freed 8K, 4% free 6903K/7175K, paused 265ms
    01-09 23:44:10.791: D/dalvikvm(1575): GC_CONCURRENT freed