Example usage for android.net.wifi WifiManager createMulticastLock

List of usage examples for android.net.wifi WifiManager createMulticastLock

Introduction

In this page you can find the example usage for android.net.wifi WifiManager createMulticastLock.

Prototype

public MulticastLock createMulticastLock(String tag) 

Source Link

Document

Create a new MulticastLock

Usage

From source file:Main.java

public static void enableMulticastLock(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    MulticastLock multicastLock = wifiManager.createMulticastLock("multicast.test");
    multicastLock.acquire();/* w  ww .  j a  v  a2s. c o  m*/
}

From source file:Main.java

public static MulticastLock openWifiBrocast(Context context) {
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    MulticastLock multicastLock = wifiManager.createMulticastLock("MediaRender");
    if (multicastLock != null) {
        multicastLock.acquire();/*from  ww w .  j a  v  a2 s.  c  o m*/
    }
    return multicastLock;
}

From source file:com.francetelecom.rd.app.nodessimulator.NodeListActivity.java

private void setupMulticast() {
    WifiManager wifiManager = (WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
    multicastLock = wifiManager.createMulticastLock("com.francetelecom.rd");
    multicastLock.setReferenceCounted(true);
    multicastLock.acquire();/*from   w  ww  . ja v  a  2  s  . com*/
}

From source file:com.tealeaf.AppFinder.java

public AppFinder(final TestAppActivity activity, Context context, final String host, final int port) {
    WifiManager wifi = (WifiManager) context.getSystemService(android.content.Context.WIFI_SERVICE);
    lock = wifi.createMulticastLock("tealeaflock");
    lock.setReferenceCounted(true);/*from w  w  w. j  a  v a  2s . c  o m*/
    lock.acquire();

    handler = new Handler();
    // don't block the main thread
    // search /projects of the given host:port for manifests
    new Thread(new Runnable() {
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    activity.showAppLoadingDialog();
                }
            });

            ArrayList<AppInfo> appInfos = new ArrayList<AppInfo>();
            String url = "http://" + host + ":" + port + "/projects";
            HTTP http = new HTTP();
            logger.log("GETTING BODY", url);
            String body = http.get(URI.create(url));
            logger.log("BODY", body);

            try {
                JSONObject json = new JSONObject(body);
                JSONArray jsonNames = json.names();
                //loop through and add to list
                for (int i = 0; i < jsonNames.length(); i++) {

                    try {
                        String projectName = jsonNames.get(i).toString();
                        JSONObject curObj = json.getJSONObject(projectName);
                        boolean isExample = false;
                        //id is used for serving
                        if (!curObj.has("id"))
                            continue;
                        String id = (String) curObj.get("id");
                        if (!curObj.has("manifest"))
                            continue;
                        JSONObject manifest = curObj.getJSONObject("manifest");
                        if (!manifest.has("title"))
                            continue;
                        String title = (String) manifest.get("title");
                        if (!manifest.has("appID"))
                            continue;
                        String appid = (String) manifest.get("appID");
                        if (manifest.has("group")) {
                            String group = (String) manifest.get("group");
                            isExample = group.equals("examples");
                        }
                        //try and fail gracefully if no icons exist, use default
                        JSONObject androidObj = manifest.getJSONObject("android");
                        JSONObject icons = androidObj.has("icons") ? androidObj.getJSONObject("icons")
                                : new JSONObject();
                        JSONArray iconNames = null;
                        int iconIndex = 0;
                        if (icons.names() != null) {
                            iconNames = icons.names();
                            //hopefully get the url for the largest icon
                            int lastNum = 0;
                            for (int j = 0; j < iconNames.length(); j++) {
                                try {
                                    int num = Integer.parseInt(iconNames.get(j).toString());
                                    if (num > lastNum) {
                                        lastNum = num;
                                        iconIndex = j;
                                    }
                                } catch (Exception e) {
                                    //some number can't parse exception
                                    logger.log(e);
                                }
                            }
                        }
                        String iconURL = "default";
                        if (icons.names() != null) {
                            iconURL = (String) icons.get(iconNames.get(iconIndex).toString());
                        }
                        if (!manifest.has("supportedOrientations"))
                            continue;
                        String orientation = (String) ((JSONArray) manifest
                                .getJSONArray("supportedOrientations")).get(0);
                        boolean isPortrait = orientation.equalsIgnoreCase("portrait");
                        AppInfo app = new AppInfo(title, appid, isPortrait, id, iconURL);
                        app.isExample = isExample;
                        appInfos.add(app);
                    } catch (Exception e) {
                        logger.log(e);
                        continue;
                    }

                }
            } catch (Exception e) {
                logger.log(e);
            }
            handler.post(new Runnable() {
                public void run() {
                    activity.dismissAppLoadingDialog();
                }
            });
            Collections.sort(appInfos, new Comparator<AppInfo>() {
                @Override
                public int compare(AppInfo lhs, AppInfo rhs) {
                    //If the apps are in the same category compare by name
                    if (lhs.isExample == rhs.isExample) {
                        return lhs.name.compareTo(rhs.name);
                    }
                    //otherwise an example app is considered "greater" than
                    //a non example app and is moved to the bottom of the list
                    return lhs.isExample ? 1 : -1;
                }

            });
            createAdapter(activity, appInfos, host, port);
        }
    }).start();
}

From source file:com.laer.easycast.MainActivity.java

@SuppressLint("InflateParams")
@Override/*  w w  w .  j  a v a  2 s .  com*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    View root = getLayoutInflater().inflate(R.layout.activity_main, null);

    setContentView(root);

    // Initialize the ViewPager and set an adapter
    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(new TabsStatePagerAdapter((getSupportFragmentManager())));
    final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
            getResources().getDisplayMetrics());
    pager.setPageMargin(pageMargin);
    PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
    //Expand tabs as required.
    tabs.setShouldExpand(true);
    tabs.setViewPager(pager);
    // Bind the tabs to the ViewPager

    // continued from above
    tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }
    });
    new DeviceSearch().execute();
    android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(
            android.content.Context.WIFI_SERVICE);
    lock = wifi.createMulticastLock("Airlock");
    lock.setReferenceCounted(false);
    lock.acquire();

}

From source file:com.cafbit.multicasttest.NetThread.java

/**
 * The main network loop.  Multicast DNS packets are received,
 * processed, and sent to the UI./*from   w ww . ja v a  2 s.c  o m*/
 * 
 * This loop may be interrupted by closing the multicastSocket,
 * at which time any commands in the commandQueue will be
 * processed.
 */
@Override
public void run() {
    Log.v(TAG, "starting network thread");

    localAddresses = NetUtil.getLocalAddresses();
    multicastLock = null;

    // initialize the network
    try {
        networkInterface = netUtil.getFirstWifiOrEthernetInterface();
        if (networkInterface == null) {
            throw new IOException("Your WiFi is not enabled.");
        }
        groupAddress = InetAddress.getByAddress(MDNS_ADDR);

        WifiManager wm = (WifiManager) MulticastTestActivity.mThis
                .getSystemService(MulticastTestActivity.mThis.getApplicationContext().WIFI_SERVICE);
        WifiManager.MulticastLock multicastLock = wm.createMulticastLock("mydebuginfo");
        multicastLock.acquire();

        openSocket();
    } catch (IOException e1) {
        Log.i(TAG, "IOException : " + e1.getMessage());
        return;
    }

    mReceivedTask = new ReceivedTask();
    mReceivedTask.execute("");
    try {
        mReceivedTask.get();
    } catch (InterruptedException e1) {

    } catch (ExecutionException e1) {
    }

}

From source file:com.iiitd.networking.UDPMessenger.java

public void startMessageReceiver() {
    Runnable receiver = new Runnable() {

        @Override/*from  ww w  . j av  a2 s  .c o m*/
        public void run() {
            WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (wim != null) {
                MulticastLock mcLock = wim.createMulticastLock(TAG);
                mcLock.acquire();
            }

            byte[] buffer = new byte[BUFFER_SIZE];
            DatagramPacket rPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket rSocket;

            try {
                rSocket = new MulticastSocket(MULTICAST_PORT);
            } catch (IOException e) {
                Log.d(DEBUG_TAG, "Impossible to create a new MulticastSocket on port " + MULTICAST_PORT);
                e.printStackTrace();
                return;
            }

            while (receiveMessages) {
                try {
                    rSocket.receive(rPacket);
                } catch (IOException e1) {
                    Log.d(DEBUG_TAG, "There was a problem receiving the incoming message.");
                    e1.printStackTrace();
                    continue;
                }

                if (!receiveMessages)
                    break;

                byte data[] = rPacket.getData();
                int i;
                for (i = 0; i < data.length; i++) {
                    if (data[i] == '\0')
                        break;
                }

                String messageText;

                try {
                    messageText = new String(data, 0, i, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    Log.d(DEBUG_TAG, "UTF-8 encoding is not supported. Can't receive the incoming message.");
                    e.printStackTrace();
                    continue;
                }

                try {
                    incomingMessage = new Message(messageText, rPacket.getAddress());
                } catch (IllegalArgumentException ex) {
                    Log.d(DEBUG_TAG, "There was a problem processing the message: " + messageText);
                    ex.printStackTrace();
                    continue;
                }

                incomingMessageHandler.post(getIncomingMessageAnalyseRunnable());
            }
        }

    };

    receiveMessages = true;
    if (receiverThread == null)
        receiverThread = new Thread(receiver);

    if (!receiverThread.isAlive())
        receiverThread.start();
}

From source file:com.example.dds_subscriber.DDS_Subscriber.java

@Override
public void onCreate(Bundle savedInstanceState) {

    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    mcastLock = wifi.createMulticastLock("Tablet");
    mcastLock.acquire();/*from ww w .j av a2 s  . c  o m*/

    // open CoreDX DDS license file:
    BufferedReader br = null;
    String license = new String("<");
    try {
        Log.i("Debug", "...Opening License");
        br = new BufferedReader(new InputStreamReader(this.getAssets().open("coredx_dds.lic")));
    } catch (IOException e) {
        Log.i("Debug", "...License did not open");
        Log.e("Tablet", e.getMessage());
    }
    if (br != null) {
        String ln;
        try {
            while ((ln = br.readLine()) != null) {
                license = new String(license + ln + "\n");
            }
        } catch (IOException e) {
            Log.e("Tablet", e.getMessage());
        }
    }
    license = new String(license + ">");
    Log.i("Tablet", "...License seems to be good");

    Log.i("Tablet", "Creating Subscriber");
    class TestDataReaderListener implements DataReaderListener {

        @Override
        public long get_nil_mask() {
            return 0;
        }

        @Override
        public void on_requested_deadline_missed(DataReader dr, RequestedDeadlineMissedStatus status) {
            System.out.println(" @@@@@@@@@@@     REQUESTED DEADLINE MISSED    @@@@@");
            System.out.println(" @@@@@@@@@@@                                  @@@@@");
            System.out.println(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        };

        @Override
        public void on_requested_incompatible_qos(DataReader dr, RequestedIncompatibleQosStatus status) {
            System.out.println(" @@@@@@@@@@@     REQUESTED INCOMPAT QOS    @@@@@@@@");
            System.out.println(" @@@@@@@@@@@        dr      = " + dr);
            System.out.println(" @@@@@@@@@@@                               @@@@@@@@");
            System.out.println(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        };

        @Override
        public void on_sample_rejected(DataReader dr, SampleRejectedStatus status) {
        };

        @Override
        public void on_liveliness_changed(DataReader dr, LivelinessChangedStatus status) {
            TopicDescription td = dr.get_topicdescription();
            System.out.println(" @@@@@@@@@@@     LIVELINESS CHANGED      @@@@@@@@@@");
        }

        @Override
        public void on_subscription_matched(DataReader dr, SubscriptionMatchedStatus status) {
            TopicDescription td = dr.get_topicdescription();
            System.out.println(" @@@@@@@@@@@     SUBSCRIPTION MATCHED    @@@@@@@@@@");
            System.out.println(
                    " @@@@@@@@@@@        topic   = " + td.get_name() + " (type: " + td.get_type_name() + ")");
            System.out.println(" @@@@@@@@@@@        current = " + status.get_current_count());
            System.out.println(" @@@@@@@@@@@                             @@@@@@@@@@");
            System.out.println(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        }

        @Override
        public void on_sample_lost(DataReader dr, SampleLostStatus status) {
            System.out.println(" @@@@@@@@@@@   SAMPLE LOST    @@@@@@@@@@");
        };

        @Override
        public void on_data_available(DataReader dr) {
            TopicDescription td = dr.get_topicdescription();
            dataDDSDataReader data_message = (dataDDSDataReader) dr;
            System.out.println(" @@@@@@@@@@@     DATA AVAILABLE          @@@@@@@@@@");
            System.out.println(
                    " @@@@@@@@@@@        topic = " + td.get_name() + " (type: " + td.get_type_name() + ")");

            samples = new dataDDSSeq();
            SampleInfoSeq si = new SampleInfoSeq();

            ReturnCode_t retval = data_message.take(samples, si, 100, coredx.DDS_ANY_SAMPLE_STATE,
                    coredx.DDS_ANY_VIEW_STATE, coredx.DDS_ANY_INSTANCE_STATE);
            System.out.println(" @@@@@@@@@@@        DR.read() ===> " + retval);

            if (retval == ReturnCode_t.RETCODE_OK) {
                if (samples.value == null)
                    System.out.println(" @@@@@@@@@@@        samples.value = null");
                else {
                    System.out.println(" @@@@@@@@@@@        samples.value.length= " + samples.value.length);
                    for (int i = 0; i < samples.value.length; i++) {
                        System.out.println("    State       : "
                                + (si.value[i].instance_state == coredx.DDS_ALIVE_INSTANCE_STATE ? "ALIVE"
                                        : "NOT ALIVE"));
                        System.out.println("    TimeStamp   : " + si.value[i].source_timestamp.sec + "."
                                + si.value[i].source_timestamp.nanosec);
                        System.out.println("    Handle      : " + si.value[i].instance_handle.value);
                        System.out.println("    WriterHandle: " + si.value[i].publication_handle.value);
                        System.out.println("    SampleRank  : " + si.value[i].sample_rank);
                        if (si.value[i].valid_data)
                            System.out.println("       XVel: " + samples.value[i].XVel_DDS);
                        System.out.println("       YVel: " + samples.value[i].YVel_DDS);
                        System.out.println(" CompassDir: " + samples.value[i].CompassDir_DDS);
                        System.out.println("     GPS_LT: " + samples.value[i].GPS_LT_DDS);
                        System.out.println("     GPS_LN: " + samples.value[i].GPS_LN_DDS);
                    }
                }
                data_message.return_loan(samples, si);
            } else {
            }
            System.out.println(" @@@@@@@@@@@                             @@@@@@@@@@");
            System.out.println(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        };
    }
    ;

    System.out.println("STARTING -------------------------");
    DomainParticipantFactory dpf = DomainParticipantFactory.get_instance();
    // dpf.set_license(license);
    dpf.get_default_participant_qos(dp_qos_tablet);
    DomainParticipant dp = null;

    System.out.println("CREATE PARTICIPANT ---------------");
    dp = dpf.create_participant(0, /* domain Id   */
            dp_qos_tablet,
            //null, /* default qos */
            null, /* no listener */
            0);

    if (dp == null) {
        //failed to create DomainParticipant -- bad license
        android.util.Log.e("CoreDX DDS", "Unable to create Tablet DomainParticipant.");
        //     new AlertDialog.Builder(this)
        //  .setTitle("CoreDX DDS Shapes Error")
        //  .setMessage("Unable to create Tablet DomainParticipant.\n(Bad License?)")
        //  .setNeutralButton("Close", new DialogInterface.OnClickListener() {
        //            public void onClick(DialogInterface dlg, int s) { /* do nothing */ } })
        //       .show();
    }

    SubscriberQos sub_qos_tablet = new SubscriberQos();
    Log.i("Tablet", "creating publisher/subscriber");
    sub_tablet = dp.create_subscriber(sub_qos_tablet, null, 0);

    System.out.println("REGISTERING TYPE -----------------");
    dataDDSTypeSupport ts = new dataDDSTypeSupport();
    ReturnCode_t returnValue = ts.register_type(dp, null);

    if (returnValue != ReturnCode_t.RETCODE_OK) {
        System.out.println("ERROR registering type\n");
        return;
    }

    System.out.println("CREATE TOPIC ---------------------");
    /* create a DDS Topic with the FilterMsg data type. */
    Topic topics = dp.create_topic("dataDDS", ts.get_type_name(), DDS.TOPIC_QOS_DEFAULT, null, 0);

    if (topics == null) {
        System.out.println("Error creating topic");
        return;
    }

    System.out.println("CREATE SUBSCRIBER ----------------");
    SubscriberQos sub_qos = null;
    SubscriberListener sub_listener = null;
    Subscriber sub = dp.create_subscriber(sub_qos, sub_listener, 0);

    System.out.println("READER VARIABLES ----------------");
    DataReaderQos dr_qos = new DataReaderQos();
    sub.get_default_datareader_qos(dr_qos);
    dr_qos.entity_name.value = "JAVA_DR";
    dr_qos.history.depth = 10;
    DataReaderListener dr_listener = new TestDataReaderListener();

    System.out.println("CREATE DATAREADER ----------------");
    //Create DDS Data reader
    dataDDSDataReader dr = (dataDDSDataReader) sub.create_datareader(topics, DDS.DATAREADER_QOS_DEFAULT,
            dr_listener, DDS.DATA_AVAILABLE_STATUS);

    System.out.println("DATAREADER CREATED ----------------");

    //Cheack to see if DDS Data Reader worked 
    if (dr == null) {
        System.out.println("ERROR creating data reader\n");
        //return;
    }

    while (true) {

        try {

            Thread.currentThread().sleep(1000); // 5 second sleep
        } catch (Exception e) {
            e.printStackTrace();
        }

        //     super.onCreate(savedInstanceState); 
        // setContentView(R.layout.activity_dds__subscriber);
        //  }
        //  }

        //   @Override
        //   public boolean onCreateOptionsMenu(Menu menu) {
        //  getMenuInflater().inflate(R.menu.activity_dds__subscriber, menu);
        //       return true;
        //   }

    }
}

From source file:com.mediaexplorer.remote.MexRemoteActivity.java

private void startMdns() {
    android.net.wifi.WifiManager wifi;

    wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);

    /* We need to specifically switch on get multicast packets as usually
     * they're disregarded, turn off soon as possible due to battery drain
     *//*ww  w . j ava2 s .  c  o  m*/

    lock = wifi.createMulticastLock("mexremote");
    lock.setReferenceCounted(true);
    lock.acquire();

    try {
        jmdns = JmDNS.create();
        jmdns.addServiceListener("_http._tcp.local.", listener = new ServiceListener() {
            @Override
            public void serviceResolved(ServiceEvent event) {
                if (event.getName().startsWith("Mex Webremote")) {
                    dialog.dismiss();
                    /* TODO handle multiple mex web remotes and give an option
                     * to select a particular one.
                     */
                    MexRemoteActivity.this.target_host = event.getInfo().getInetAddress().getHostAddress();
                    MexRemoteActivity.this.target_port = event.getInfo().getPort();

                    remoteFound("http://" + MexRemoteActivity.this.target_host + ":"
                            + MexRemoteActivity.this.target_port + "/");

                    /* release asap to save battery */
                    lock.release();
                }
            }

            @Override
            public void serviceRemoved(ServiceEvent event) {
                dialog.show();
                jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
            }

            @Override
            public void serviceAdded(ServiceEvent event) {
                /* Ask for the new item to be resolved */
                jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
            }

        });
    } catch (IOException exception) {
        exception.printStackTrace();
        return;
    }
}

From source file:com.google.appinventor.components.runtime.BlockyTalky.java

private void aquireMulticastLock() {
    WifiManager wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
    if (wifi != null) {
        WifiManager.MulticastLock lock = wifi.createMulticastLock(LOG_TAG);
        lock.acquire();/* www  .jav a2  s  .  co  m*/
    } else {
        Log.d(LOG_TAG, "WIFI MANAGER NULL");
    }
}