Example usage for android.bluetooth BluetoothAdapter getDefaultAdapter

List of usage examples for android.bluetooth BluetoothAdapter getDefaultAdapter

Introduction

In this page you can find the example usage for android.bluetooth BluetoothAdapter getDefaultAdapter.

Prototype

public static synchronized BluetoothAdapter getDefaultAdapter() 

Source Link

Document

Get a handle to the default local Bluetooth adapter.

Usage

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

@Override
public void onCreate() {
    super.onCreate();
    FileLog.d("=============== VoIPService STARTING ===============");
    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1
            && am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER) != null) {
        int outFramesPerBuffer = Integer
                .parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
        VoIPController.setNativeBufferSize(outFramesPerBuffer);
    } else {//from w  ww. ja va  2s .  c  o m
        VoIPController.setNativeBufferSize(
                AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)
                        / 2);
    }
    final SharedPreferences preferences = getSharedPreferences("mainconfig", MODE_PRIVATE);
    VoIPServerConfig.setConfig(preferences.getString("voip_server_config", "{}"));
    if (System.currentTimeMillis() - preferences.getLong("voip_server_config_updated", 0) > 24 * 3600000) {
        ConnectionsManager.getInstance().sendRequest(new TLRPC.TL_phone_getCallConfig(), new RequestDelegate() {
            @Override
            public void run(TLObject response, TLRPC.TL_error error) {
                if (error == null) {
                    String data = ((TLRPC.TL_dataJSON) response).data;
                    VoIPServerConfig.setConfig(data);
                    preferences.edit().putString("voip_server_config", data)
                            .putLong("voip_server_config_updated",
                                    BuildConfig.DEBUG ? 0 : System.currentTimeMillis())
                            .apply();
                }
            }
        });
    }
    try {
        controller = new VoIPController();
        controller.setConnectionStateListener(this);
        controller.setConfig(MessagesController.getInstance().callPacketTimeout / 1000.0,
                MessagesController.getInstance().callConnectTimeout / 1000.0,
                preferences.getInt("VoipDataSaving", VoIPController.DATA_SAVING_NEVER));

        cpuWakelock = ((PowerManager) getSystemService(POWER_SERVICE))
                .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "telegram-voip");
        cpuWakelock.acquire();

        btAdapter = am.isBluetoothScoAvailableOffCall() ? BluetoothAdapter.getDefaultAdapter() : null;

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ACTION_HEADSET_PLUG);
        if (btAdapter != null) {
            filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
            filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        }
        filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        filter.addAction(getPackageName() + ".END_CALL");
        filter.addAction(getPackageName() + ".DECLINE_CALL");
        filter.addAction(getPackageName() + ".ANSWER_CALL");
        registerReceiver(receiver, filter);

        ConnectionsManager.getInstance().setAppPaused(false, false);

        soundPool = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
        spConnectingId = soundPool.load(this, R.raw.voip_connecting, 1);
        spRingbackID = soundPool.load(this, R.raw.voip_ringback, 1);
        spFailedID = soundPool.load(this, R.raw.voip_failed, 1);
        spEndId = soundPool.load(this, R.raw.voip_end, 1);
        spBusyId = soundPool.load(this, R.raw.voip_busy, 1);

        am.registerMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));

        if (btAdapter != null && btAdapter.isEnabled()) {
            int headsetState = btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
            updateBluetoothHeadsetState(headsetState == BluetoothProfile.STATE_CONNECTED);
            if (headsetState == BluetoothProfile.STATE_CONNECTED)
                am.setBluetoothScoOn(true);
            for (StateListener l : stateListeners)
                l.onAudioSettingsChanged();
        }

        NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
    } catch (Exception x) {
        FileLog.e("error initializing voip controller", x);
        callFailed();
    }
}

From source file:com.hivewallet.androidclient.wallet.ui.send.SendCoinsFragment.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setRetainInstance(true);/*w  ww .  j  a va  2 s  . c  o m*/
    setHasOptionsMenu(true);

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND);
    backgroundThread.start();
    backgroundHandler = new Handler(backgroundThread.getLooper());

    if (savedInstanceState != null) {
        restoreInstanceState(savedInstanceState);
    } else {
        final Intent intent = activity.getIntent();
        final String action = intent.getAction();
        final Uri intentUri = intent.getData();
        final String scheme = intentUri != null ? intentUri.getScheme() : null;
        final String mimeType = intent.getType();

        if ((Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
                && intentUri != null && "bitcoin".equals(scheme)) {
            initStateFromBitcoinUri(intentUri);
        } else if ((NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
                && PaymentProtocol.MIMETYPE_PAYMENTREQUEST.equals(mimeType)) {
            final NdefMessage ndefMessage = (NdefMessage) intent
                    .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)[0];
            final byte[] ndefMessagePayload = Nfc.extractMimePayload(PaymentProtocol.MIMETYPE_PAYMENTREQUEST,
                    ndefMessage);
            initStateFromPaymentRequest(mimeType, ndefMessagePayload);
        } else if ((Intent.ACTION_VIEW.equals(action))
                && PaymentProtocol.MIMETYPE_PAYMENTREQUEST.equals(mimeType)) {
            final byte[] paymentRequest = BitcoinIntegration.paymentRequestFromIntent(intent);

            if (intentUri != null)
                initStateFromIntentUri(mimeType, intentUri);
            else if (paymentRequest != null)
                initStateFromPaymentRequest(mimeType, paymentRequest);
            else
                throw new IllegalArgumentException();
        } else if (intent.hasExtra(SendCoinsActivity.INTENT_EXTRA_PAYMENT_INTENT)) {
            initStateFromIntentExtras(intent.getExtras());
        } else {
            updateStateFrom(PaymentIntent.blank());
        }
    }
}

From source file:com.mobilinkd.tncconfig.TncConfig.java

@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    }//  www.  j a va  2 s.c  om
    setContentView(R.layout.activity_main);

    if (D)
        Log.e(TAG, "+++ ON CREATE +++");

    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    mBluetoothDeviceView = (TextView) findViewById(R.id.bluetooth_device_text);
    mFirmwareVersionView = (TextView) findViewById(R.id.firmware_version_text);
}

From source file:com.lewa.crazychapter11.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    //set to full screen
    // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);

    ///set to no title
    // requestWindowFeature(Window.FEATURE_NO_TITLE);
    // acionBar = getSupportActionBar();
    // acionBar = getActionBar();
    // acionBar.hide();

    // Window win = getWindow();
    //          win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //          win.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS  | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);  
    //          win.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);  
    // win.setStatusBarColor(Color.TRANSPARENT);  
    // win.setNavigationBarColor(Color.TRANSPARENT);

    /*//*from   w  w w  .ja va 2 s .  c  o  m*/
       win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
       win.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS  | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);  
       win.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN  | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION  | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);  
       win.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);  
       win.setStatusBarColor(Color.TRANSPARENT);  
       win.setNavigationBarColor(Color.TRANSPARENT);
    //*/

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    /* setTheme(R.style.CrazyTheme); */
    AddGameBtn();
    AddNoification();
    LookupContact();
    AddServiceBtn();
    broadcastMain();
    mediaPlayerMain();
    mediaRecordSoundMain();
    cameraMain();
    recordvideoMain();
    queMySql();
    TestFragment();
    justForTest();
    LoadJson();
    AddTestBtn();
    AddUsageStatsBtn();
    AddPeopleProvideBtn();
    getInput();

    ////just for test shutdown broadcast receiver
    IntentFilter mIntentFilter = new IntentFilter("android.intent.action.ACTION_SHUTDOWN");
    mIntentFilter.addAction("com.lewa.alarm.test");
    mIntentFilter.addAction("android.provider.Telephony.SECRET_CODE");
    mIntentFilter.addAction("android.intent.action.SCREEN_ON");
    mIntentFilter.addAction("android.intent.action.SCREEN_OFF");
    mShoutdown = new shutdownReceiver();
    registerReceiver(mShoutdown, mIntentFilter);
    ////test      

    preferences = getSharedPreferences("crazyit", MODE_WORLD_WRITEABLE | MODE_WORLD_READABLE);
    editor = preferences.edit();

    preferencestime = getSharedPreferences("RMS_Shutdown_time", MODE_WORLD_WRITEABLE | MODE_WORLD_READABLE);
    editortime = preferencestime.edit();

    SharedShutdownTimeRead();

    AddSharedPreBtn();

    etNum = (EditText) findViewById(R.id.etNum);

    // //
    int maxLength = 4;

    InputFilter[] fArray = new InputFilter[1];

    fArray[0] = new InputFilter.LengthFilter(maxLength);

    etNum.setFilters(fArray);
    // //

    calThread = new CalThread();
    calThread.start();

    Log.i("algerheMain", "MainActivity onCreate in!!");
    String page = getString(R.string.str_page, "345", "24");
    Log.i("algerheMain", "page=" + page);

    // /just for test here
    ComponentName comp = getIntent().getComponent();
    show_txt = (EditText) findViewById(R.id.show_txt);
    show_txt.setText(
            "??" + comp.getPackageName() + " \n ??" + comp.getClassName());

    ////MD5 check item
    ///1.IMEI
    TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    String szImei = TelephonyMgr.getDeviceId();
    String m_szSIMSerialNm = TelephonyMgr.getSimSerialNumber();
    CellLocation m_location = TelephonyMgr.getCellLocation();
    String m_Line1Number = TelephonyMgr.getLine1Number();
    String m_OperatorName = TelephonyMgr.getSimOperatorName();
    Log.i("algerheTelephonyMgr", "szImei=" + szImei);
    Log.i("algerheTelephonyMgr", "m_szSIMSerialNm=" + m_szSIMSerialNm);
    Log.i("algerheTelephonyMgr", "m_location=" + m_location);
    Log.i("algerheTelephonyMgr", "m_Line1Number=" + m_Line1Number);
    Log.i("algerheTelephonyMgr", "m_OperatorName=" + m_OperatorName);

    Log.i("algerheMain01", "szImei=" + szImei);
    Log.i("algerheMain01", "m_szSIMSerialNm=" + m_szSIMSerialNm);

    ///2.Pseudo-Unique ID
    String m_szDevIDShort = "35" + //we make this look like a valid IMEI 
            Build.BOARD.length() % 10 + Build.BRAND.length() % 10 + Build.CPU_ABI.length() % 10
            + Build.DEVICE.length() % 10 + Build.DISPLAY.length() % 10 + Build.HOST.length() % 10
            + Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 + Build.MODEL.length() % 10
            + Build.PRODUCT.length() % 10 + Build.TAGS.length() % 10 + Build.TYPE.length() % 10
            + Build.USER.length() % 10; //13 digits

    Log.i("algerheMain01", "m_szDevIDShort=" + m_szDevIDShort);

    ///3. Android ID
    String m_szAndroidID = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
    Log.i("algerheMain01", "m_szAndroidID=" + m_szAndroidID);

    ///4.WLAN MAC Address string
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    String m_szWLANMAC = "unknow_wifi_mac";
    if (wm != null && wm.getConnectionInfo() != null) {
        m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
    }

    Log.i("algerheMain01", "m_szWLANMAC=" + m_szWLANMAC);

    ///5.BT MAC Address string
    BluetoothAdapter m_BluetoothAdapter = null; // Local Bluetooth adapter      
    m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    String m_szBTMAC = m_BluetoothAdapter.getAddress();

    Log.i("algerheMain01", "m_szBTMAC=" + m_szBTMAC);

    ///6.sim serial number .getSimSerialNumber()

    // /

    ///reflect test   
    checkMethod();

    // */
    final Intent alarmIntent = new Intent();
    Log.i("algerheMain00", "isLewaRom=" + isLewaRom(this, alarmIntent));

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x4567) {
                String languageStr = null;
                String countryStr = null;

                Locale[] locList = Locale.getAvailableLocales();

                for (int i = 0; i < locList.length; i++) {
                    languageStr += locList[i].getLanguage();
                    countryStr += locList[i].getCountry();
                }
                // show_txt = (EditText) findViewById(R.id.show_txt);
                show_txt.setText("" + languageStr + " \n " + countryStr);
            } else if (msg.what == 0x2789) {
                Log.i("algerheAlarm", "send alarm message in time=" + System.currentTimeMillis() + "\n action="
                        + alarmIntent.getAction());

                // sendBroadcast(alarmIntent);
            }
        }
    };

    // String strApkPath = intent.getStringExtra("apkPath");
    //         String strCmd = "pm install -r " + strApkPath;
    //         try {
    //             Process install = Runtime.getRuntime().exec(strCmd);
    //             Log.d(TAG, "install = " + install + ", strCmd =" + strCmd);
    //         }catch (Exception ex){
    //             Log.d(TAG, ex.getMessage());
    //         }   
    // */
}

From source file:com.sdingba.su.lanya.MainActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {

    case REQUEST_SELECT_DEVICE:
        //When the DeviceListActivity return, with the selected device address
        if (resultCode == Activity.RESULT_OK && data != null) {
            //???
            String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
            mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);

            Log.d(TAG, "... onActivityResultdevice.address==" + mDevice + "mserviceValue" + mService);
            ((TextView) findViewById(R.id.deviceName)).setText(mDevice.getName() + " - connecting");
            mService.connect(deviceAddress);
        }//ww  w .j a  v a  2  s .  c  o m
        break;
    case REQUEST_ENABLE_BT:
        // When the request to enable Bluetooth returns
        if (resultCode == Activity.RESULT_OK) {

            Toast.makeText(this, "Bluetooth has turned on for onActivityResult ", Toast.LENGTH_SHORT).show();

        } else {
            // User did not enable Bluetooth or an error occurred
            Log.d(TAG, "BT not enabled");
            Toast.makeText(this, "Problem in BT Turning ON for onActivityResult", Toast.LENGTH_SHORT).show();
            Log.i(TAG, "finish(); is acticiyty");
            finish();
        }
        break;
    default:
        Log.e(TAG, "wrong request code");
        break;
    }
}

From source file:com.saulcintero.moveon.services.MoveOnService.java

@Override
public void onCreate() {
    super.onCreate();

    mContext = getApplicationContext();/*from ww w. j  a  v a  2s.c  om*/
    prefs = PreferenceManager.getDefaultSharedPreferences(mContext);

    tts = TextToSpeechUtils.getInstance();
    tts.initTTS(mContext);

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    showNotification();

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    mHandler = new Handler();
    mHandler.postDelayed(mRunnable, 0);

    acquireWakeLock();

    mStepDetector = new StepDetector();
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    registerDetector();

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mComponentName = new ComponentName(getPackageName(), MediaButtonEventReceiver.class.getName());

    mSettingsObserver = new SettingsObserver(this, mContext, mComponentName);
    mContentResolver = getContentResolver();
    mContentResolver.registerContentObserver(Settings.System.getUriFor(MEDIA_BUTTON_RECEIVER), false,
            mSettingsObserver);

    registerMediaButtonReceiver();

    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    registerReceiver(mReceiverScreenOff, filter);

    IntentFilter filter2 = new IntentFilter("android.intent.action.ACTION_SCREEN_REFRESH");
    registerReceiver(mReceiverRefreshScreenPreferences, filter2);

    IntentFilter filter3 = new IntentFilter("android.intent.action.ACTION_SAY_PRACTICE_INFORMATION");
    registerReceiver(mReceiverSayInformation, filter3);

    IntentFilter filter4 = new IntentFilter("android.intent.action.STEP_COUNTER");
    registerReceiver(mReceiverStepCounter, filter4);

    IntentFilter filter5 = new IntentFilter("android.intent.action.BEAT_COUNTER");
    registerReceiver(mReceiverBeatCounter, filter5);

    IntentFilter filter6 = new IntentFilter("android.intent.action.EMPTY_SENSOR_MANAGER");
    registerReceiver(mReceiverEmptySensorManager, filter6);

    IntentFilter filter7 = new IntentFilter("android.intent.action.ACTION_PLAY_SOUND");
    registerReceiver(mReceiverPlaySound, filter7);

    IntentFilter filter8 = new IntentFilter("android.intent.action.ACTION_REFRESH_SENSITIVITY");
    registerReceiver(mReceiverRefreshSensitivity, filter8);

    IntentFilter filter9 = new IntentFilter("android.intent.action.CADENCE");
    registerReceiver(mReceiverCadence, filter9);

    IntentFilter filter10 = new IntentFilter("android.intent.action.REGISTER_MEDIA_BUTTON_STATUS");
    registerReceiver(mReceiverRegisterMediaButton, filter10);

    IntentFilter filter11 = new IntentFilter("android.intent.action.UNREGISTER_MEDIA_BUTTON_STATUS");
    registerReceiver(mReceiverUnregisterMediaButton, filter11);

    mStepCounter = new StepCounter(mContext);
    mStepDetector.addStepListener(mStepCounter);

    mTimeManager = new TimeManager(mContext);
    mDistanceManager = new DistanceManager(mContext);

    locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    listener = new mGpsListener();
    locListener = new mLocationListener();
    locMgr.addGpsStatusListener(listener);
    locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_UPDATE_TIME_INTERVAL,
            GPS_UPDATE_DISTANCE_INTERVAL, locListener);
}

From source file:net.sourceforge.servestream.fragment.UrlListFragment.java

private void showPopup(View v, UriBean uri) {
    mSelectedMenuItem = uri;/*from   w  ww  .j  a va 2  s .  c om*/

    PopupMenu popup = new PopupMenu(getActivity(), v);
    Menu menu = popup.getMenu();
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.uri_list_uri_actions, menu);
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        menu.removeItem(R.id.menu_autostart_on_bluetooth);
    }
    popup.setOnMenuItemClickListener(mPopupMenuOnMenuItemClickListener);
    popup.show();
}

From source file:net.sourceforge.servestream.fragment.BrowseFragment.java

private void showPopup(View v, UriBean uri) {
    mSelectedMenuItem = uri;//from  w  ww.j ava  2 s.  co  m

    PopupMenu popup = new PopupMenu(getActivity(), v);
    Menu menu = popup.getMenu();
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.browse_uri_actions, menu);
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        menu.removeItem(R.id.menu_autostart_on_bluetooth);
    }
    popup.setOnMenuItemClickListener(mPopupMenuOnMenuItemClickListener);
    popup.show();
}

From source file:com.trigger_context.Main_Service.java

private void takeAction(String mac, InetAddress ip) {
    noti("comes to ", mac);

    SharedPreferences conditions = getSharedPreferences(mac, MODE_PRIVATE);
    Map<String, ?> cond_map = conditions.getAll();
    Set<String> key_set = cond_map.keySet();
    Main_Service.main_Service.noti(cond_map.toString(), "");
    if (key_set.contains("SmsAction")) {
        String number = conditions.getString("SmsActionNumber", null);
        String message = conditions.getString("SmsActionMessage", null);

        try {/*from ww w.  j  av a2s  .  com*/
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(number, null, message, null, null);
            noti("Sms Sent To : ", "" + number);
        } catch (Exception e) {
            noti("Sms Sending To ", number + "Failed");
        }
    }
    if (key_set.contains("OpenWebsiteAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Open_Url.class);
        dialogIntent.putExtra("urlAction", (String) cond_map.get("urlAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);

    }
    if (key_set.contains("ToggleAction")) {
        if (key_set.contains("bluetoothAction") && conditions.getBoolean("bluetoothAction", false)) {
            final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            bluetoothAdapter.enable();
        } else if (key_set.contains("bluetoothAction")) {
            final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            bluetoothAdapter.disable();
        }
        if (key_set.contains("wifiAction") && conditions.getBoolean("wifiAction", false)) {
            final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wm.setWifiEnabled(true);
        } else if (key_set.contains("wifiAction")) {
            final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wm.setWifiEnabled(false);
        }
    }
    if (key_set.contains("TweetAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Post_Tweet.class);
        dialogIntent.putExtra("tweetTextAction", (String) cond_map.get("tweetTextAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);
    }

    if (key_set.contains("EmailAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Email_Client.class);
        dialogIntent.putExtra("toAction", (String) cond_map.get("toAction"));
        dialogIntent.putExtra("subjectAction", (String) cond_map.get("subjectAction"));
        dialogIntent.putExtra("emailMessageAction", (String) cond_map.get("emailMessageAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);
    }
    if (key_set.contains("RemoteServerCmd")) {

        String text = conditions.getString("cmd", null);
        new Thread(new SendData("224.0.0.1", 9876, text)).start();
    }
    // network activities from here.
    // in all network actions send username first
    if (key_set.contains("FileTransferAction"))

    {
        String path = conditions.getString("filePath", null);
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 1
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataOutputStream out = null;
            out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(1);
            sendFile(out, path);

            noti("Sent " + path + " file to :",
                    getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    if (key_set.contains("ccfMsgAction"))

    {
        String msg = conditions.getString("ccfMsg", null);
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 2 is msg
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataOutputStream out = null;
            out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(2);
            out.writeUTF(msg);

            noti("Sent msg : '" + msg + "'", "to : "
                    + getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (key_set.contains("sync")) {
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 3 is sync
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(3);
            senderSync(in, out, Environment.getExternalStorageDirectory().getPath() + "/TriggerSync/");

            noti("Synced with:",
                    getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:org.envirocar.app.activity.MainActivity.java

protected void updateStartStopButton() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    if (adapter != null && adapter.isEnabled()) { // was requirementsFulfilled
        createStartStopUtil().updateStartStopButtonOnServiceStateChange(navDrawerItems[START_STOP_MEASUREMENT]);
    } else {//from   w w w . ja va2  s.co m
        createStartStopUtil().defineButtonContents(navDrawerItems[START_STOP_MEASUREMENT], false,
                R.drawable.not_available, getString(R.string.pref_bluetooth_disabled),
                getString(R.string.menu_start));
    }

    navDrawerAdapter.notifyDataSetChanged();
}