Example usage for android.content BroadcastReceiver BroadcastReceiver

List of usage examples for android.content BroadcastReceiver BroadcastReceiver

Introduction

In this page you can find the example usage for android.content BroadcastReceiver BroadcastReceiver.

Prototype

public BroadcastReceiver() 

Source Link

Usage

From source file:es.glasspixel.wlanaudit.fragments.ScanFragment.java

/**
 * Sets up the logic to execute when a scan is complete. This is done this
 * way because the SCAN_RESULTS_AVAILABLE_ACTION must be caught by a
 * BroadCastReceiver./* w w  w. j  a  v  a 2s.c  o m*/
 */
private void setupNetworkScanCallBack() {
    IntentFilter i = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    mCallBackReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // Network scan complete, datasource needs to be updated and
            // ListView refreshed

            List<ScanResult> res = mWifiManager.getScanResults();
            mIsScanning = false;

            if (saved_keys_fragment != null && getSherlockActivity() != null) {
                mCallback.scanCompleted();
                if (mWifiManager.getScanResults().size() > 0) {
                    list_view.setAdapter(new WifiNetworkAdapter(getSherlockActivity(),
                            R.layout.network_list_element_layout, res));
                } else {
                    list_view.setEmptyView(getSherlockActivity().findViewById(R.id.empty));
                }
            }

        }
    };
    getSherlockActivity().registerReceiver(mCallBackReceiver, i);
}

From source file:com.example.ronald.tracle.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new DownloadTask().execute("https://flifo-qa.api.aero/flifo/v3/flight/sin/sq/998/d");
    /*//ww  w  .jav a2 s .  c  o m
    Parsing of data from previous activity
     */
    String username = getIntent().getStringExtra("name");
    String password = getIntent().getStringExtra("password");
    String alias = getIntent().getStringExtra("alias");
    myUser = username;
    pw = password;
    /*
    Declare your layout here
     */

    Button sendBtn = (Button) findViewById(R.id.buttonSendAll);

    TextView nametv = (TextView) findViewById(R.id.username);
    TextView emailtv = (TextView) findViewById(R.id.email);
    emailtv.setText(username);
    nametv.setText(alias);

    // Initializing Toolbar and setting it as the actionbar
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //Initializing NavigationView
    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        // This method will trigger on item Click of navigation menu
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            //Checking if the item is in checked state or not, if not make it in checked state
            if (menuItem.isChecked())
                menuItem.setChecked(false);
            else
                menuItem.setChecked(true);

            //Closing drawer on item click
            drawerLayout.closeDrawers();

            //Check to see which item was being clicked and perform appropriate action
            switch (menuItem.getItemId()) {

            //Replacing the main content with ContentFragment Which is our Inbox View;
            case R.id.home:
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                startActivity(intent);
                return true;
            case R.id.explore:
                Intent intente = new Intent(MainActivity.this, SlideTab.class);
                startActivity(intente);
                return true;
            case R.id.network:
                Intent intentk = new Intent(MainActivity.this, SlideTab.class);
                startActivity(intentk);
                return true;
            case R.id.announcement:
                Intent intenti = new Intent(MainActivity.this, AnnounceActivity.class);
                startActivity(intenti);
                return true;
            case R.id.setting:
                String username = "";
                String pw = "";
                String PREFS_LOGIN_USERNAME_KEY = "";
                String PREFS_LOGIN_PASSWORD_KEY = "";
                PrefUtils.saveToPrefs(getApplication(), PREFS_LOGIN_USERNAME_KEY, username);
                PrefUtils.saveToPrefs(getApplication(), PREFS_LOGIN_PASSWORD_KEY, pw);
                System.exit(0);
                return true;
            // For rest of the options we just show a toast on click
            default:
                Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
                return true;

            }
        }
    });

    // Initializing Drawer Layout and ActionBarToggle
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.openDrawer, R.string.closeDrawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

            super.onDrawerOpened(drawerView);
        }
    };

    //Setting the actionbarToggle to drawer layout
    drawerLayout.setDrawerListener(actionBarDrawerToggle);

    //Toast.makeText(this, "username: "+username+" pw: "+password, Toast.LENGTH_SHORT).show();

    //calling sync state is necessay or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();

    /*
    This is the initial step in getting back the token from GCM
     */
    //mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
            if (sentToken) {
                //  mInformationTextView.setText(getString(R.string.gcm_send_message));
            } else {
                // mInformationTextView.setText(getString(R.string.token_error_message));
            }
        }
    };
    //mInformationTextView = (TextView) findViewById(R.id.informationTextView);

    /*
    Check play services, if not GCM won't work.
     */
    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        Bundle localBundle = new Bundle();
        localBundle.putString("name", username);
        localBundle.putString("password", password);
        intent.putExtras(localBundle);
        startService(intent);
    }

}

From source file:de.lespace.apprtc.activity.ConnectActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_connect);

    // Get setting keys.
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    keyprefFrom = getString(R.string.pref_from_key);
    keyprefVideoCallEnabled = getString(R.string.pref_videocall_key);
    keyprefResolution = getString(R.string.pref_resolution_key);
    keyprefFps = getString(R.string.pref_fps_key);
    keyprefCaptureQualitySlider = getString(R.string.pref_capturequalityslider_key);
    keyprefVideoBitrateType = getString(R.string.pref_startvideobitrate_key);
    keyprefVideoBitrateValue = getString(R.string.pref_startvideobitratevalue_key);
    keyprefVideoCodec = getString(R.string.pref_videocodec_key);
    keyprefHwCodecAcceleration = getString(R.string.pref_hwcodec_key);
    keyprefCaptureToTexture = getString(R.string.pref_capturetotexture_key);
    keyprefAudioBitrateType = getString(R.string.pref_startaudiobitrate_key);
    keyprefAudioBitrateValue = getString(R.string.pref_startaudiobitratevalue_key);
    keyprefAudioCodec = getString(R.string.pref_audiocodec_key);
    keyprefNoAudioProcessingPipeline = getString(R.string.pref_noaudioprocessing_key);
    keyprefAecDump = getString(R.string.pref_aecdump_key);
    keyprefOpenSLES = getString(R.string.pref_opensles_key);
    keyprefDisplayHud = getString(R.string.pref_displayhud_key);
    keyprefTracing = getString(R.string.pref_tracing_key);
    keyprefRoomServerUrl = getString(R.string.pref_room_server_url_key);
    keyprefRoomList = getString(R.string.pref_room_list_key);

    // Video call enabled flag.
    boolean videoCallEnabled = sharedPref.getBoolean(keyprefVideoCallEnabled,
            Boolean.valueOf(getString(R.string.pref_videocall_default)));

    String wssUrl = sharedPref.getString(keyprefRoomServerUrl,
            getString(R.string.pref_room_server_url_default));
    from = sharedPref.getString(keyprefFrom, getString(R.string.pref_from_default));
    // Get default codecs.
    String videoCodec = sharedPref.getString(keyprefVideoCodec, getString(R.string.pref_videocodec_default));
    String audioCodec = sharedPref.getString(keyprefAudioCodec, getString(R.string.pref_audiocodec_default));

    // Check HW codec flag.
    boolean hwCodec = sharedPref.getBoolean(keyprefHwCodecAcceleration,
            Boolean.valueOf(getString(R.string.pref_hwcodec_default)));

    // Check Capture to texture.
    boolean captureToTexture = sharedPref.getBoolean(keyprefCaptureToTexture,
            Boolean.valueOf(getString(R.string.pref_capturetotexture_default)));

    // Check Disable Audio Processing flag.
    boolean noAudioProcessing = sharedPref.getBoolean(keyprefNoAudioProcessingPipeline,
            Boolean.valueOf(getString(R.string.pref_noaudioprocessing_default)));

    // Check Disable Audio Processing flag.
    boolean aecDump = sharedPref.getBoolean(keyprefAecDump,
            Boolean.valueOf(getString(R.string.pref_aecdump_default)));

    // Check OpenSL ES enabled flag.
    boolean useOpenSLES = sharedPref.getBoolean(keyprefOpenSLES,
            Boolean.valueOf(getString(R.string.pref_opensles_default)));

    // Check for mandatory permissions.
    missingPermissions = new ArrayList();

    for (String permission : MANDATORY_PERMISSIONS) {
        if (checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            missingPermissions.add(permission);
        }/*from  w w  w .j  a va  2  s.  c om*/
    }
    requestPermission();

    networkchangeBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getFlags() == 0) {
                SignalingService.appRTCClient.resetWebsocket();
            }
            if (intent.getFlags() == 1) {
                SignalingService.appRTCClient.reconnect();
                Toast.makeText(context, "network is online:" + intent.getFlags(), Toast.LENGTH_LONG).show();
            }
        }
    };

    // Registering BroadcastReceiver
    registerNetworkChangeReceiver();

    // Get video resolution from settings.
    int videoWidth = 0;
    int videoHeight = 0;
    String resolution = sharedPref.getString(keyprefResolution, getString(R.string.pref_resolution_default));
    String[] dimensions = resolution.split("[ x]+");
    if (dimensions.length == 2) {
        try {
            videoWidth = Integer.parseInt(dimensions[0]);
            videoHeight = Integer.parseInt(dimensions[1]);
        } catch (NumberFormatException e) {
            videoWidth = 0;
            videoHeight = 0;
            Log.e(TAG, "Wrong video resolution setting: " + resolution);
        }
    }

    // Get camera fps from settings.
    int cameraFps = 0;
    String fps = sharedPref.getString(keyprefFps, getString(R.string.pref_fps_default));
    String[] fpsValues = fps.split("[ x]+");
    if (fpsValues.length == 2) {
        try {
            cameraFps = Integer.parseInt(fpsValues[0]);
        } catch (NumberFormatException e) {
            Log.e(TAG, "Wrong camera fps setting: " + fps);
        }
    }

    // Check capture quality slider flag.
    boolean captureQualitySlider = sharedPref.getBoolean(keyprefCaptureQualitySlider,
            Boolean.valueOf(getString(R.string.pref_capturequalityslider_default)));

    // Get video and audio start bitrate.
    int videoStartBitrate = 0;
    String bitrateTypeDefault = getString(R.string.pref_startvideobitrate_default);
    String bitrateType = sharedPref.getString(keyprefVideoBitrateType, bitrateTypeDefault);
    if (!bitrateType.equals(bitrateTypeDefault)) {
        String bitrateValue = sharedPref.getString(keyprefVideoBitrateValue,
                getString(R.string.pref_startvideobitratevalue_default));
        videoStartBitrate = Integer.parseInt(bitrateValue);
    }
    int audioStartBitrate = 0;
    bitrateTypeDefault = getString(R.string.pref_startaudiobitrate_default);
    bitrateType = sharedPref.getString(keyprefAudioBitrateType, bitrateTypeDefault);
    if (!bitrateType.equals(bitrateTypeDefault)) {
        String bitrateValue = sharedPref.getString(keyprefAudioBitrateValue,
                getString(R.string.pref_startaudiobitratevalue_default));
        audioStartBitrate = Integer.parseInt(bitrateValue);
    }

    // Check statistics display option.
    boolean displayHud = sharedPref.getBoolean(keyprefDisplayHud,
            Boolean.valueOf(getString(R.string.pref_displayhud_default)));

    boolean tracing = sharedPref.getBoolean(keyprefTracing,
            Boolean.valueOf(getString(R.string.pref_tracing_default)));

    // Log.d(TAG, "Connecting from " + from + " at URL " + wssUrl);

    if (validateUrl(wssUrl)) {
        Uri uri = Uri.parse(wssUrl);
        intent = new Intent(this, ConnectActivity.class);
        intent.setData(uri);
        intent.putExtra(CallActivity.EXTRA_VIDEO_CALL, videoCallEnabled);
        intent.putExtra(CallActivity.EXTRA_VIDEO_WIDTH, videoWidth);
        intent.putExtra(CallActivity.EXTRA_VIDEO_HEIGHT, videoHeight);
        intent.putExtra(CallActivity.EXTRA_VIDEO_FPS, cameraFps);
        intent.putExtra(CallActivity.EXTRA_VIDEO_CAPTUREQUALITYSLIDER_ENABLED, captureQualitySlider);
        intent.putExtra(CallActivity.EXTRA_VIDEO_BITRATE, videoStartBitrate);
        intent.putExtra(CallActivity.EXTRA_VIDEOCODEC, videoCodec);
        intent.putExtra(CallActivity.EXTRA_HWCODEC_ENABLED, hwCodec);
        intent.putExtra(CallActivity.EXTRA_CAPTURETOTEXTURE_ENABLED, captureToTexture);
        intent.putExtra(CallActivity.EXTRA_NOAUDIOPROCESSING_ENABLED, noAudioProcessing);
        intent.putExtra(CallActivity.EXTRA_AECDUMP_ENABLED, aecDump);
        intent.putExtra(CallActivity.EXTRA_OPENSLES_ENABLED, useOpenSLES);
        intent.putExtra(CallActivity.EXTRA_AUDIO_BITRATE, audioStartBitrate);
        intent.putExtra(CallActivity.EXTRA_AUDIOCODEC, audioCodec);
        intent.putExtra(CallActivity.EXTRA_DISPLAY_HUD, displayHud);
        intent.putExtra(CallActivity.EXTRA_TRACING, tracing);
        intent.putExtra(CallActivity.EXTRA_RUNTIME, runTimeMs);
    }

    roomListView = (ListView) findViewById(R.id.room_listview);
    roomListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    connectButton = (ImageButton) findViewById(R.id.connect_button);
    connectButton.setOnClickListener(connectListener);

    // If an implicit VIEW intent is launching the app, go directly to that URL.
    //final Intent intent = getIntent();
    Uri wsurl = Uri.parse(wssUrl);
    //intent.getData();
    // Log.d(TAG, "connecting to:" + wsurl.toString());
    if (wsurl == null) {
        logAndToast(getString(R.string.missing_wsurl));
        Log.e(TAG, "Didn't get any URL in intent!");
        setResult(RESULT_CANCELED);
        finish();
        return;
    }

    if (from == null || from.length() == 0) {
        logAndToast(getString(R.string.missing_from));
        Log.e(TAG, "Incorrect from in intent!");
        setResult(RESULT_CANCELED);
        finish();
        return;
    }

    peerConnectionParameters = new PeerConnectionClient.PeerConnectionParameters(videoCallEnabled, tracing,
            videoWidth, videoHeight, cameraFps, videoStartBitrate, videoCodec, hwCodec, captureToTexture,
            audioStartBitrate, audioCodec, noAudioProcessing, aecDump, useOpenSLES);

    Intent intent = getIntent();
    Log.i(TAG, "created apprtc with uri:" + wsurl.toString() + " from:" + from);

    Log.i(TAG, "intent.EXTRA_TO:" + intent.getStringExtra(RTCConnection.EXTRA_TO));
    Log.i(TAG, "intent.EXTRA_FROM:" + intent.getStringExtra(RTCConnection.EXTRA_FROM));
    Log.i(TAG, "intent.EXTRA_INITIATOR:" + intent.getBooleanExtra(RTCConnection.EXTRA_INITIATOR, false));

    if (intent.getStringExtra(RTCConnection.EXTRA_TO) != null
            && !intent.getStringExtra(RTCConnection.EXTRA_TO).equals("")) {

        RTCConnection.to = intent.getStringExtra(RTCConnection.EXTRA_TO);
        RTCConnection.from = intent.getStringExtra(RTCConnection.EXTRA_FROM);
        RTCConnection.initiator = intent.getBooleanExtra(RTCConnection.EXTRA_INITIATOR, false);
        ;
        connectToUser();
    }

    /*  if(intent.getStringExtra(RTCConnection.EXTRA_TO)!=null
            && !intent.getStringExtra(RTCConnection.EXTRA_TO).equals("")){
            
          RTCConnection.to = intent.getStringExtra(RTCConnection.EXTRA_TO);
         // RTCConnection.from = intent.getStringExtra(RTCConnection.EXTRA_FROM);
          RTCConnection.initiator = intent.getBooleanExtra(RTCConnection.EXTRA_INITIATOR,false);;
            
      Intent serviceIntent = new Intent(this,SignalingService.class);
      serviceIntent.putExtra(RTCConnection.EXTRA_FROM, RTCConnection.to);
            
     //WebRTC-Signaling
     startService(intent);
    }*/

}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java

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

    prefs = getSharedPreferences("com.roamprocess1.roaming4world", Context.MODE_PRIVATE);
    stored_chatuserNumber = "com.roamprocess1.roaming4world.stored_chatuserNumber";
    stored_user_mobile_no = "com.roamprocess1.roaming4world.user_mobile_no";
    stored_user_country_code = "com.roamprocess1.roaming4world.user_country_code";
    stored_supportnumber = "com.roamprocess1.roaming4world.support_no";
    stored_server_ipaddress = "com.roamprocess1.roaming4world.server_ip";

    usernum = prefs.getString(stored_user_country_code, "") + prefs.getString(stored_user_mobile_no, "");

    System.out.println("MessageActivity.java before if statement of savedInstanceState ");
    if (savedInstanceState == null) {
        // During initial setup, plug in the details fragment.
        System.out.println("MessageActivity.java after if statement of savedInstanceState ");
        detailFragment = new MessageFragment();
        detailFragment.setArguments(getIntent().getExtras());

        getSupportFragmentManager().beginTransaction().add(android.R.id.content, detailFragment).commit();
        detailFragment.setOnQuitListener(this);
    }//w  w w .j  a  va 2s  .c o m

    if (getConnectivityStatus(getApplicationContext()) == TYPE_NOT_CONNECTED)
        dialogBoxNoInternet();

    broadcastReceiver_socket_userStatus = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();

            Log.d("Receiver", "Broadcast received: " + action);

            if (action.equals(ChatSocket.USER_STATUS)) {
                String state = intent.getExtras().getString(ChatSocket.USER_STATUS);
                Log.d("Receiver state", state + " @");
                setStatus(state);
            }

        }
    };

    broadcastReceiver_lost = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            Log.d("broadcastReceiver_lost", "called");
            tv_userStatus.setText("");
        }
    };

    registerReceiver(broadcastReceiver_lost, new IntentFilter("INTERNET_LOST"));
    registerReceiver(broadcastReceiver_socket_userStatus, new IntentFilter(ChatSocket.USER_STATUS));

}

From source file:com.esminis.server.library.activity.main.MainPresenterImpl.java

private void showInstallFinished(Context context) {
    if (view == null) {
        return;/*  w  w  w . j  a v  a 2 s.  c  o m*/
    }
    if (installError != null) {
        view.setMessage(true, false, null,
                context.getString(R.string.server_installation_failed, installError.getMessage()));
        return;
    }
    view.showMainContent();
    view.setDocumentRoot(getRootDirectory(activity));
    view.setPort(getPort(activity), true);
    view.setInstallPackages(installPackageManager.getInstalled(), installPackageManager.getNewest());
    receiverManager.add(context, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION),
            new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    resetNetwork();
                }
            });
    receiverManager.add(context, new IntentFilter(MainActivity.getIntentActionServerStatus(context)),
            new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    if (view != null
                            && MainActivity.getIntentActionServerStatus(context).equals(intent.getAction())) {
                        Bundle extras = intent.getExtras();
                        if (extras != null && extras.containsKey("errorLine")) {
                            resetLog();
                        } else {
                            if (extras != null && extras.getBoolean("running")) {
                                view.showButton(MainView.BUTTON_STOP);
                                view.setStatusLabel(Html.fromHtml(serverControl.getServerRunningLabel(activity,
                                        extras.getString("address"))));
                            } else {
                                view.showButton(MainView.BUTTON_START);
                                view.setStatusLabel(activity.getString(R.string.server_stopped));
                            }
                        }
                    }
                }

            });
    resetNetwork();
    serverStatus();
}

From source file:gcm.play.android.samples.com.gcmquickstart.MainFragment.java

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {

    fileMaker = new FileMaker();

    mTextureView = (TextureView) view.findViewById(R.id.texture);
    mIntervalToRecordText = (EditText) view.findViewById(R.id.intervalToRecord);
    mLengthToRecordText = (EditText) view.findViewById(R.id.secondToRecord);
    mNumberOfRecordingsText = (EditText) view.findViewById(R.id.numRecordingsToMake);

    mButtonVideo = (Button) view.findViewById(R.id.video);
    mButtonAutoVideo = (Button) view.findViewById(R.id.video_repeat);

    mButtonAutoVideo.setOnClickListener(this);
    mButtonVideo.setOnClickListener(this);

    focusValueText = (TextView) view.findViewById(R.id.focusValue);
    mSeekBar = (SeekBar) view.findViewById(R.id.seekBar);
    mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override/* w w w  .  j  a  v a2  s. c o m*/
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            focusValueText.setText(String.format("%d > %d", i, mLastSentFocusValue));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mLastSentFocusValue = seekBar.getProgress();
            focusValueText.setText(String.format("%d -> %d", seekBar.getProgress(), mLastSentFocusValue));

            new SendMessageTask(getContext()).execute(MainFragment.UPDATE_FOCUS_MESSAGE, "-1",
                    Float.toString(seekBar.getProgress()));
        }
    });

    mRepeatRecordingHandler = new Handler();

    // Enable when a connection to the server has been made.
    mButtonVideo.setEnabled(false);
    mButtonAutoVideo.setEnabled(false);

    // Set defaults for these.
    mIntervalToRecordText.setText(Double.toString(DEFAULT_RECORD_INTERVAL));
    mLengthToRecordText.setText(Double.toString(DEFAULT_RECORD_LENGTH));
    mNumberOfRecordingsText.setText(Integer.toString(DEFAULT_TIMES_TO_RECORD));

    //// FOR COMMUNICATION
    // Registering BroadcastReceiver

    mRegistrationProgressBar = (ProgressBar) view.findViewById(R.id.registrationProgressBar);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
            if (sentToken) {
                mInformationTextView.setText(getString(R.string.gcm_send_message));
                mButtonVideo.setEnabled(true);
                mButtonAutoVideo.setEnabled(true);
            } else {
                mInformationTextView.setText(getString(R.string.token_error_message));
            }
        }
    };
    mTogglePlaybackReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("dei", "Message received intent HIT");

            if (intent.getExtras().get("message").equals(START_RECORDING_MESSAGE)) {
                // Start recording.
                toggleVideoRecording(true, intent.getExtras().getInt("id"));
            } else {
                toggleVideoRecording(false, intent.getExtras().getInt("id"));
            }
        }
    };

    mReconnectBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // No longer allow recording until connection is reestablished.
            mButtonVideo.setEnabled(false);
            mButtonAutoVideo.setEnabled(false);
            mInformationTextView.setText("Record failed. Trying to reconnect to server.");

            // Try reestablishing connection.
            intent = new Intent(MainFragment.this.getActivity(), RegistrationIntentService.class);
            MainFragment.this.getActivity().startService(intent);
        }
    };

    mInformationTextView = (TextView) view.findViewById(R.id.informationTextView);
    mNumRecordingsTextView = (TextView) view.findViewById(R.id.numRecordingsTextView);

    registerReceiver();

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this.getActivity(), RegistrationIntentService.class);
        this.getActivity().startService(intent);
    }
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

public static void DownloadFromUrl(final String media, final String messageId, final Context ctx,
        final ImageView container, final Object object, final String timelineId, final String localId,
        final Long fileSize) {

    new AsyncTask<Void, Void, Boolean>() {
        private boolean retry = true;
        private Bitmap imageDownloaded;
        private BroadcastReceiver mDownloadCancelReceiver;
        private HttpGet job;
        private AccountManager am;
        private Account account;
        private String authToken;

        @Override/*from w w  w  .ja v  a  2s.  c  o m*/
        protected void onPreExecute() {
            IntentFilter downloadFilter = new IntentFilter(ConstantKeys.BROADCAST_CANCEL_PROCESS);
            mDownloadCancelReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String localIdToClose = (String) intent.getExtras().get(ConstantKeys.LOCALID);
                    if (localId.equals(localIdToClose)) {
                        try {
                            job.abort();
                        } catch (Exception e) {
                            log.debug("The process was canceled");
                        }
                        cancel(false);
                    }
                }
            };

            // registering our receiver
            ctx.getApplicationContext().registerReceiver(mDownloadCancelReceiver, downloadFilter);
        }

        @Override
        protected void onCancelled() {
            File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG);
            File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP);

            if (file1.exists()) {
                file1.delete();
            }
            if (file2.exists()) {
                file2.delete();
            }

            file1 = null;
            file2 = null;
            System.gc();
            try {
                ctx.getApplicationContext().unregisterReceiver(mDownloadCancelReceiver);
            } catch (Exception e) {
                log.debug("Receriver unregister from another code");
            }

            for (int i = 0; i < AppUtils.getlistOfDownload().size(); i++) {
                if (AppUtils.getlistOfDownload().get(i).equals(localId)) {
                    AppUtils.getlistOfDownload().remove(i);
                }
            }

            DataBasesAccess.getInstance(ctx.getApplicationContext()).MessagesDataBaseWriteTotal(localId, 100);

            Intent intent = new Intent();
            intent.setAction(ConstantKeys.BROADCAST_DIALOG_DOWNLOAD_FINISH);
            intent.putExtra(ConstantKeys.LOCALID, localId);
            ctx.sendBroadcast(intent);

            if (object != null) {
                ((ProgressDialog) object).dismiss();
            }
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG);
                File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP);
                // firt we are goint to search the local files
                if ((!file1.exists()) && (!file2.exists())) {
                    account = AccountUtils.getAccount(ctx.getApplicationContext(), false);
                    am = (AccountManager) ctx.getSystemService(Context.ACCOUNT_SERVICE);
                    authToken = ConstantKeys.STRING_DEFAULT;
                    authToken = am.blockingGetAuthToken(account, ctx.getString(R.string.account_type), true);

                    MessagingClientService messageService = new MessagingClientService(
                            ctx.getApplicationContext());

                    URL urlObj = new URL(Preferences.getServerProtocol(ctx), Preferences.getServerAddress(ctx),
                            Preferences.getServerPort(ctx), ctx.getString(R.string.url_get_content));

                    String url = ConstantKeys.STRING_DEFAULT;
                    url = Uri.parse(urlObj.toString()).buildUpon().build().toString() + timelineId + "/"
                            + messageId + "/" + "content";

                    job = new HttpGet(url);
                    // first, get free space
                    FreeUpSpace(ctx, fileSize);
                    messageService.getContent(authToken, media, messageId, timelineId, localId, false, false,
                            fileSize, job);
                }

                if (file1.exists()) {
                    imageDownloaded = decodeSampledBitmapFromPath(file1.getAbsolutePath(), 200, 200);
                } else if (file2.exists()) {
                    imageDownloaded = ThumbnailUtils.createVideoThumbnail(file2.getAbsolutePath(),
                            MediaStore.Images.Thumbnails.MINI_KIND);
                }

                if (imageDownloaded == null) {
                    return false;
                }
                return true;
            } catch (Exception e) {
                deleteFiles();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            // We have the media
            try {
                ctx.getApplicationContext().unregisterReceiver(mDownloadCancelReceiver);
            } catch (Exception e) {
                log.debug("Receiver was closed on cancel");
            }

            if (!(localId.contains(ConstantKeys.AVATAR))) {
                for (int i = 0; i < AppUtils.getlistOfDownload().size(); i++) {
                    if (AppUtils.getlistOfDownload().get(i).equals(localId)) {
                        AppUtils.getlistOfDownload().remove(i);
                    }
                }

                DataBasesAccess.getInstance(ctx.getApplicationContext()).MessagesDataBaseWriteTotal(localId,
                        100);

                Intent intent = new Intent();
                intent.setAction(ConstantKeys.BROADCAST_DIALOG_DOWNLOAD_FINISH);
                intent.putExtra(ConstantKeys.LOCALID, localId);
                ctx.sendBroadcast(intent);
            }

            if (object != null) {
                ((ProgressDialog) object).dismiss();
            }

            // Now the only container could be the avatar in edit screen
            if (container != null) {
                if (imageDownloaded != null) {
                    container.setImageBitmap(imageDownloaded);
                } else {
                    deleteFiles();
                    imageDownloaded = decodeSampledBitmapFromResource(ctx.getResources(),
                            R.drawable.ic_error_loading, 200, 200);
                    container.setImageBitmap(imageDownloaded);
                    Toast.makeText(ctx.getApplicationContext(),
                            ctx.getApplicationContext().getText(R.string.donwload_fail), Toast.LENGTH_SHORT)
                            .show();
                }
            } else {
                showMedia(localId, ctx, (ProgressDialog) object);
            }

        }

        private void deleteFiles() {
            File file1 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_JPG);
            File file2 = new File(FileUtils.getDir(), localId + ConstantKeys.EXTENSION_3GP);
            if (file1.exists()) {
                file1.delete();
            }
            if (file2.exists()) {
                file2.delete();
            }
        }

    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.numenta.taurus.instance.InstanceListFragment.java

/**
 * InstanceListFragment constructor//from w w w.  j a  v a  2 s .c om
 */
public InstanceListFragment() {
    // Listen for new instance data
    _instanceDataChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateInstanceData();
        }
    };

    // Listen for favorites changes
    _favoritesChangedReceiver = new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent event) {
            if (_instanceFilter == InstanceFilter.Favorites) {
                filterFavorites();
            } else {
                clearFilter();
            }
        }
    };
}

From source file:com.mobiperf.MeasurementScheduler.java

@Override
public void onCreate() {
    Logger.d("Service onCreate called");
    PhoneUtils.setGlobalContext(this.getApplicationContext());
    phoneUtils = PhoneUtils.getPhoneUtils();
    phoneUtils.registerSignalStrengthListener();
    this.checkin = new Checkin(this);
    this.checkinRetryIntervalSec = Config.MIN_CHECKIN_RETRY_INTERVAL_SEC;
    this.checkinRetryCnt = 0;
    this.checkinTask = new CheckinTask();

    this.pauseRequested = true;
    this.stopRequested = false;
    this.measurementExecutor = Executors.newSingleThreadExecutor();
    this.taskQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new TaskComparator());
    this.pendingTasks = new ConcurrentHashMap<MeasurementTask, Future<MeasurementResult>>();

    // expect it to be the same size as the queue
    this.currentSchedule = new Hashtable<String, MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE);

    this.notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    this.alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    this.resourceCapManager = new ResourceCapManager(Config.DEFAULT_BATTERY_THRESH_PRECENT, this);

    restoreState();//  w  ww  .  ja  v a 2  s. co m

    // Register activity specific BroadcastReceiver here
    IntentFilter filter = new IntentFilter();
    filter.addAction(UpdateIntent.PREFERENCE_ACTION);
    filter.addAction(UpdateIntent.MSG_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_RETRY_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);

    broadcastReceiver = new BroadcastReceiver() {
        // Handles various broadcast intents.

        // If traffic is paused by RRCTrafficControl (because a RRC test is
        // running), we do not perform the checkin, since sending interfering
        // traffic makes the RRC inference task abort and restart the current
        // test as the traffic may have altered the phone's RRC state.
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(UpdateIntent.PREFERENCE_ACTION)) {
                updateFromPreference();
            } else if (intent.getAction().equals(UpdateIntent.CHECKIN_ACTION)
                    || intent.getAction().equals(UpdateIntent.CHECKIN_RETRY_ACTION)
                            && !RRCTrafficControl.checkIfPaused()) {
                Logger.d("Checkin intent received");
                handleCheckin(false);
            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_ACTION)
                    && !RRCTrafficControl.checkIfPaused()) {
                Logger.d("MeasurementIntent intent received");
                handleMeasurement();
            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION)) {
                Logger.d("MeasurementIntent update intent received");
                if (intent.getIntExtra(UpdateIntent.PROGRESS_PAYLOAD,
                        Config.INVALID_PROGRESS) == Config.MEASUREMENT_END_PROGRESS) {
                    if (intent.getStringExtra(UpdateIntent.ERROR_STRING_PAYLOAD) != null) {
                        failedMeasurementCnt++;
                    } else {
                        // Process result
                        completedMeasurementCnt++;
                    }
                    if (intent.getStringExtra(UpdateIntent.RESULT_PAYLOAD) != null) {
                        Logger.d("Measurement result intent received");
                        saveResultToFile(intent.getStringExtra(UpdateIntent.RESULT_PAYLOAD));

                    }
                    updateResultsConsole(intent);
                }
            } else if (intent.getAction().equals(UpdateIntent.MSG_ACTION)) {
                String msg = intent.getExtras().getString(UpdateIntent.STRING_PAYLOAD);
                Date now = Calendar.getInstance().getTime();
                insertStringToConsole(systemConsole, now + "\n\n" + msg);
            }
        }
    };
    this.registerReceiver(broadcastReceiver, filter);
    // TODO(mdw): Make this a user-selectable option
    addIconToStatusBar();
}

From source file:eu.power_switch.gui.fragment.alarm_clock.SleepAsAndroidFragment.java

@Override
public void onCreateViewEvent(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_sleep_as_android, container, false);

    setHasOptionsMenu(true);// w w  w  .j  a  va  2s  . co m

    final RecyclerViewFragment recyclerViewFragment = this;

    Switch switchOnOff = (Switch) rootView.findViewById(R.id.switch_on_off);
    switchOnOff.setChecked(SmartphonePreferencesHandler.getSleepAsAndroidEnabled());
    switchOnOff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (buttonView.isPressed()) {
                SmartphonePreferencesHandler.setSleepAsAndroidEnabled(isChecked);
            }
        }
    });

    layout_installed = (LinearLayout) rootView.findViewById(R.id.layout_installed);
    layout_not_installed = (LinearLayout) rootView.findViewById(R.id.layout_not_installed);

    IconicsImageView getFromPlayStore = (IconicsImageView) rootView.findViewById(R.id.get_from_play_store);
    getFromPlayStore.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SleepAsAndroidHelper.openPlayStorePage(getActivity());
        }
    });

    spinnerEventType = (Spinner) rootView.findViewById(R.id.spinner_sleep_as_android_event);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
            R.array.sleep_as_android_event_names, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerEventType.setAdapter(adapter);
    SpinnerInteractionListener spinnerInteractionListener = new SpinnerInteractionListener() {
        @Override
        public void onItemSelectedByUser(AdapterView<?> parent, View view, int pos, long id) {
            updateUI();
        }
    };
    spinnerEventType.setOnItemSelectedListener(spinnerInteractionListener);
    spinnerEventType.setOnTouchListener(spinnerInteractionListener);

    recyclerViewActions = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    recyclerViewAdapter = new ActionRecyclerViewAdapter(getContext(), actions);
    recyclerViewAdapter.setOnDeleteClickListener(new ActionRecyclerViewAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View itemView, final int position) {
            new AlertDialog.Builder(getContext()).setTitle(R.string.delete).setMessage(R.string.are_you_sure)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                actions.remove(position);
                                DatabaseHandler.setAlarmActions(SLEEP_AS_ANDROID_ALARM_EVENT
                                        .getById(spinnerEventType.getSelectedItemPosition()), actions);
                                StatusMessageHandler.showInfoMessage(recyclerViewFragment.getRecyclerView(),
                                        R.string.action_removed, Snackbar.LENGTH_LONG);
                            } catch (Exception e) {
                                StatusMessageHandler.showErrorMessage(recyclerViewFragment.getRecyclerView(),
                                        e);
                            }

                            recyclerViewAdapter.notifyDataSetChanged();
                        }
                    }).setNeutralButton(android.R.string.cancel, null).show();
        }
    });
    recyclerViewActions.setAdapter(recyclerViewAdapter);
    StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(getSpanCount(),
            StaggeredGridLayoutManager.VERTICAL);
    recyclerViewActions.setLayoutManager(layoutManager);

    addActionFAB = (FloatingActionButton) rootView.findViewById(R.id.add_fab);
    addActionFAB.setImageDrawable(IconicsHelper.getAddIcon(getActivity(),
            ContextCompat.getColor(getActivity(), android.R.color.white)));
    addActionFAB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AddSleepAsAndroidAlarmEventActionDialog addAlarmEventActionDialog = AddSleepAsAndroidAlarmEventActionDialog
                    .newInstance(spinnerEventType.getSelectedItemPosition());
            addAlarmEventActionDialog.setTargetFragment(recyclerViewFragment, 0);
            addAlarmEventActionDialog.show(getActivity().getSupportFragmentManager(), null);
        }
    });

    // BroadcastReceiver to get notifications from background service if room data has changed
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(this, "received intent: " + intent.getAction());

            if (LocalBroadcastConstants.INTENT_ALARM_EVENT_ACTION_ADDED.equals(intent.getAction())) {
                updateUI();
            } else {
                updateUI();
            }
        }
    };
}