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:com.nadmm.airports.aeronav.ChartsDownloadFragment.java

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

    mFilter = new IntentFilter();
    mFilter.addAction(AeroNavService.ACTION_GET_CHARTS);
    mFilter.addAction(AeroNavService.ACTION_CHECK_CHARTS);
    mFilter.addAction(AeroNavService.ACTION_COUNT_CHARTS);

    mReceiver = new BroadcastReceiver() {

        @Override//from  www  .j a  v  a2s . co m
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
            case AeroNavService.ACTION_GET_CHARTS:
                onChartDownload(context, intent);
                break;
            case AeroNavService.ACTION_CHECK_CHARTS:
                onChartDelete(context, intent);
                break;
            case AeroNavService.ACTION_COUNT_CHARTS:
                onChartCount(context, intent);
                break;
            }
        }
    };

    mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mSelectedRow == null) {
                mStop = false;
                int total = (Integer) v.getTag(R.id.DTPP_CHART_TOTAL);
                int avail = (Integer) v.getTag(R.id.DTPP_CHART_AVAIL);
                if (avail < total) {
                    if (mIsOk && !mExpired) {
                        confirmStartDownload(v);
                    } else {
                        UiUtils.showToast(getActivity(), "Cannot start download");
                    }
                } else {
                    confirmChartDelete(v);
                }
            } else if (v == mSelectedRow) {
                confirmStopDownload();
            }
        }
    };
}

From source file:com.google.android.gcm.demo.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedState) {
    super.onCreate(savedState);
    setContentView(R.layout.activity_main);
    mLogger = new Logger(this);
    mLogsUI = (TextView) findViewById(R.id.logs);
    mLoggerCallback = new BroadcastReceiver() {
        @Override/*  w w w .  ja  va  2 s . c  o m*/
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
            case LoggingService.ACTION_CLEAR_LOGS:
                mLogsUI.setText("");
                break;
            case LoggingService.ACTION_LOG:
                StringBuilder stringBuilder = new StringBuilder();
                String newLog = intent.getStringExtra(LoggingService.EXTRA_LOG_MESSAGE);
                String oldLogs = Html.toHtml(new SpannableString(mLogsUI.getText()));
                appendFormattedLogLine(newLog, stringBuilder);
                stringBuilder.append(oldLogs);
                mLogsUI.setText(Html.fromHtml(stringBuilder.toString()));
                List<Fragment> fragments = getSupportFragmentManager().getFragments();
                for (Fragment fragment : fragments) {
                    if (fragment instanceof RefreshableFragment && fragment.isVisible()) {
                        ((RefreshableFragment) fragment).refresh();
                    }
                }
                break;
            }
        }
    };

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerView = (FrameLayout) findViewById(R.id.navigation_drawer);
    mDrawerMenu = (ListView) findViewById(R.id.navigation_drawer_menu);
    mDrawerScrim = findViewById(R.id.navigation_drawer_scrim);

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    TypedArray colorPrimaryDark = getTheme().obtainStyledAttributes(new int[] { R.attr.colorPrimaryDark });
    mDrawerLayout.setStatusBarBackgroundColor(colorPrimaryDark.getColor(0, 0xFF000000));
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    colorPrimaryDark.recycle();

    ImageView drawerHeader = new ImageView(this);
    drawerHeader.setImageResource(R.drawable.drawer_gcm_logo);
    mDrawerMenu.addHeaderView(drawerHeader);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // Set the drawer width accordingly with the guidelines: window_width - toolbar_height.
        toolbar.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View view, int left, int top, int right, int bottom, int oldLeft,
                    int oldTop, int oldRight, int oldBottom) {
                if (left == 0 && top == 0 && right == 0 && bottom == 0) {
                    return;
                }
                DisplayMetrics metrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(metrics);
                float logicalDensity = metrics.density;
                int maxWidth = (int) Math.ceil(320 * logicalDensity);
                DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) mDrawerView.getLayoutParams();
                int newWidth = view.getWidth() - view.getHeight();
                params.width = (newWidth > maxWidth ? maxWidth : newWidth);
                mDrawerView.setLayoutParams(params);
            }
        });
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        mDrawerView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
            @Override
            public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                // Set scrim height to match status bar height.
                mDrawerScrim.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                        insets.getSystemWindowInsetTop()));
                return insets;
            }
        });
    }

    int activeItemIndicator = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            ? android.R.layout.simple_list_item_activated_1
            : android.R.layout.simple_list_item_checked;

    mMainMenu = new MainMenu(this);
    mDrawerMenu.setOnItemClickListener(this);
    mDrawerMenu.setAdapter(new ArrayAdapter<>(getSupportActionBar().getThemedContext(), activeItemIndicator,
            android.R.id.text1, mMainMenu.getEntries()));

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open,
            R.string.drawer_close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            // The user learned how to open the drawer. Do not open it for him anymore.
            getAppPreferences().edit().putBoolean(PREF_OPEN_DRAWER_AT_STARTUP, false).apply();
            super.onDrawerOpened(drawerView);
        }
    };

    boolean activityResumed = (savedState != null);
    boolean openDrawer = getAppPreferences().getBoolean(PREF_OPEN_DRAWER_AT_STARTUP, true);
    int lastScreenId = getAppPreferences().getInt(PREF_LAST_SCREEN_ID, 0);
    selectItem(lastScreenId);
    if (!activityResumed && openDrawer) {
        mDrawerLayout.openDrawer(mDrawerView);
    }
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    /*
     * Here we check if the Activity was created by the user clicking on one of our GCM
     * notifications:
     * 1. Check if the action of the intent used to launch the Activity.
     * 2. Print out any additional data sent with the notification. This is included as extras
     *  on the intent.
     */
    Intent launchIntent = getIntent();
    if ("gcm_test_app_notification_click_action".equals(launchIntent.getAction())) {
        Bundle data = launchIntent.getExtras();
        data.isEmpty(); // Force the bundle to unparcel so that toString() works
        String format = getResources().getString(R.string.notification_intent_received);
        mLogger.log(Log.INFO, String.format(format, data));
    }
}

From source file:com.kyleszombathy.sms_scheduler.MessageAlarmReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    this.context = context;
    boolean sendSuccessFlag = true;

    // Get wakelock
    Intent service = new Intent(context, MessageAlarmReceiver.class);

    // Start the service, keeping the device awake while it is launching.
    Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
    startWakefulService(context, service);

    // Get data from intent
    ArrayList<String> phoneList = intent.getStringArrayListExtra("pNum");
    String messageContent = intent.getStringExtra("message");
    int alarmNumber = intent.getIntExtra("alarmNumber", -1);
    ArrayList<String> nameList = intent.getStringArrayListExtra("nameList");

    // Split message, regardless if needed - just in case I have the message length number wrong
    final ArrayList<String> messageArrayList = smsManager.divideMessage(messageContent);

    // Sends to multiple recipients
    for (int i = 0; i < phoneList.size(); i++) {
        // Send message and retrieve
        boolean result = sendSMSMessage(phoneList.get(i), messageArrayList);
        if (!result) {
            sendSuccessFlag = false;/*from w  w w  .j  av a  2  s . c  om*/
        }
    }

    /* Register for SMS send action */
    context.getApplicationContext().registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String result = "";
            final String[] TRANSMISSION_TYPE = { "Transmission successful", "Transmission failed", "Radio off",
                    "No PDU defined", "No service" };

            switch (getResultCode()) {
            case Activity.RESULT_OK:
                result = TRANSMISSION_TYPE[0];
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                result = TRANSMISSION_TYPE[1];
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                result = TRANSMISSION_TYPE[2];
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                result = TRANSMISSION_TYPE[3];
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                result = TRANSMISSION_TYPE[4];
                break;
            }
            Log.i(TAG, result + " for message " + messageArrayList.toString());
            // Handle error
            if (!Objects.equals(result, TRANSMISSION_TYPE[0])) {
                //messageSendSuccess[0] = false;
            }
        }
    }, new IntentFilter(SENT));

    // Create notification message
    String notificationMessage = Tools.createSentString(context, nameList, 1, sendSuccessFlag);

    // Send notification if message send successfull
    if (sendSuccessFlag) {
        sendNotification(context, notificationMessage, messageContent, true, nameList);
    } else {
        sendNotification(context, notificationMessage, messageContent, false, nameList);
    }
    // Archive, regardless of send success or not
    markAsSent(context, notificationMessage, alarmNumber);
    // Release wakelock
    completeWakefulIntent(service);
}

From source file:com.google.android.apps.muzei.MuzeiWallpaperService.java

@Override
public void onCreate() {
    super.onCreate();
    if (UserManagerCompat.isUserUnlocked(this)) {
        initialize();/*  w  w  w .  j a  v  a2 s  .co  m*/
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        mUnlockReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                initialize();
                unregisterReceiver(this);
            }
        };
        IntentFilter filter = new IntentFilter(Intent.ACTION_USER_UNLOCKED);
        registerReceiver(mUnlockReceiver, filter);
    }
}

From source file:com.google.android.gms.drive.sample.conflict.MainActivity.java

@Override
protected void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.activity_main);

    groceryListEditText = (EditText) findViewById(R.id.editText);
    updateGroceryListButton = (Button) findViewById(R.id.button);

    updateGroceryListButton.setOnClickListener(new View.OnClickListener() {
        @Override//from w w w . j a  v  a 2 s . c  om
        public void onClick(View view) {
            if (groceryListContents != null) {
                groceryListContents.reopenForWrite(getGoogleApiClient())
                        .setResultCallback(updateDriveContensCallback);
                // Disable update button to prevent double taps.
                updateGroceryListButton.setEnabled(false);
            }
        }
    });

    // When conflicts are resolved, update the EditText with the resolved list
    // then open the contents so it contains the resolved list.
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConflictResolver.CONFLICT_RESOLVED)) {
                Log.d(TAG, "Received intent to update edit text.");
                String resolvedStr = intent.getStringExtra("conflictResolution");
                groceryListEditText.setText(resolvedStr);
                // Open {@code groceryListFile} in read only mode to update
                // {@code groceryListContents} to current base state.
                groceryListFile.open(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null)
                        .setResultCallback(driveContentsCallback);
            }
        }
    };
}

From source file:eu.power_switch.gui.dialog.AddSsidDialog.java

@NonNull
@Override/*from www.ja v a  2  s.  co  m*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ArrayList<String> connections = new ArrayList<>();

            for (ScanResult scanResult : mainWifi.getScanResults()) {
                if (scanResult.SSID != null && !scanResult.SSID.isEmpty()) {
                    connections.add(scanResult.SSID);
                }
            }

            updateSSIDs(connections);

            layoutLoading.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
        }
    };

    mainWifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);

    LayoutInflater inflater = getActivity().getLayoutInflater();
    contentView = inflater.inflate(R.layout.dialog_add_ssid, null);
    builder.setView(contentView);

    editText_ssid = (TextInputEditText) contentView.findViewById(R.id.editText_ssid);
    editText_ssid.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            checkValidity();
        }
    });

    final IconicsImageView refresh = (IconicsImageView) contentView.findViewById(R.id.button_refresh);
    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mainWifi.isWifiEnabled()) {
                refresh.startAnimation(AnimationHandler.getRotationClockwiseAnimation(getContext()));
                refreshSsids();
            } else {
                Toast.makeText(getActivity(), "WiFi disabled!", Toast.LENGTH_LONG).show();
            }
        }
    });

    layoutLoading = (LinearLayout) contentView.findViewById(R.id.layoutLoading);

    listView = (ListView) contentView.findViewById(R.id.listView);
    ssidAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_multiple_choice, ssids);
    listView.setAdapter(ssidAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            checkValidity();
        }
    });

    builder.setTitle(R.string.add_ssids);
    builder.setPositiveButton(R.string.add, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            try {
                sendSsidAddedBroadcast(getContext(), getSelectedSSIDs());
            } catch (Exception e) {
                StatusMessageHandler.showErrorMessage(getTargetFragment().getView().findViewById(R.id.listView),
                        e);
            }
        }
    });

    builder.setNeutralButton(android.R.string.cancel, null);

    setPositiveButtonVisibility(false);

    dialog = builder.create();
    dialog.setCanceledOnTouchOutside(false); // prevent close dialog on touch outside window
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    dialog.show();

    defaultTextColor = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).getTextColors()
            .getDefaultColor();

    checkValidity();

    refreshSsids();

    return dialog;
}

From source file:eu.power_switch.gui.fragment.configure_geofence.ConfigureGeofenceDialogPage3ExitActionsFragment.java

@Nullable
@Override/*w ww  .  j  a  v  a  2 s.c  om*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.dialog_fragment_configure_geofence_page_3, container, false);

    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            sendActionsChangedBroadcast(getContext(), currentExitActions);
        }
    };

    final Fragment fragment = this;
    FloatingActionButton addActionFAB = (FloatingActionButton) rootView.findViewById(R.id.add_action);
    addActionFAB.setImageDrawable(IconicsHelper.getAddIcon(getActivity(),
            ContextCompat.getColor(getActivity(), android.R.color.white)));
    addActionFAB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AddGeofenceExitActionDialog addGeofenceExitActionDialog = new AddGeofenceExitActionDialog();
            addGeofenceExitActionDialog.setTargetFragment(fragment, 0);
            addGeofenceExitActionDialog.show(getActivity().getSupportFragmentManager(), null);
        }
    });

    currentExitActions = new ArrayList<>();
    actionRecyclerViewAdapter = new ActionRecyclerViewAdapter(getActivity(), currentExitActions);
    actionRecyclerViewAdapter.setOnDeleteClickListener(new ActionRecyclerViewAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {
            currentExitActions.remove(position);
            actionRecyclerViewAdapter.notifyDataSetChanged();
            sendActionsChangedBroadcast(getContext(), currentExitActions);
        }
    });
    RecyclerView recyclerViewTimerActions = (RecyclerView) rootView
            .findViewById(R.id.recyclerview_list_of_actions);
    recyclerViewTimerActions.setAdapter(actionRecyclerViewAdapter);
    StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1,
            StaggeredGridLayoutManager.VERTICAL);
    recyclerViewTimerActions.setLayoutManager(layoutManager);

    Bundle args = getArguments();
    if (args != null && args.containsKey(ConfigureGeofenceDialog.GEOFENCE_ID_KEY)) {
        long geofenceId = args.getLong(ConfigureGeofenceDialog.GEOFENCE_ID_KEY);
        initializeData(geofenceId);
    }

    sendActionsChangedBroadcast(getContext(), currentExitActions);

    return rootView;
}

From source file:eu.power_switch.gui.fragment.configure_geofence.ConfigureGeofenceDialogPage2EnterActionsFragment.java

@Nullable
@Override/*from  ww w.  ja  va  2s  .  c o m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.dialog_fragment_configure_geofence_page_2, container, false);

    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            sendActionsChangedBroadcast(getContext(), currentEnterActions);
        }
    };

    final Fragment fragment = this;
    FloatingActionButton addActionFAB = (FloatingActionButton) rootView.findViewById(R.id.add_action);
    addActionFAB.setImageDrawable(IconicsHelper.getAddIcon(getActivity(),
            ContextCompat.getColor(getActivity(), android.R.color.white)));
    addActionFAB.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AddGeofenceEnterActionDialog addGeofenceEnterActionDialog = new AddGeofenceEnterActionDialog();
            addGeofenceEnterActionDialog.setTargetFragment(fragment, 0);
            addGeofenceEnterActionDialog.show(getActivity().getSupportFragmentManager(), null);
        }
    });

    currentEnterActions = new ArrayList<>();
    actionRecyclerViewAdapter = new ActionRecyclerViewAdapter(getActivity(), currentEnterActions);
    actionRecyclerViewAdapter.setOnDeleteClickListener(new ActionRecyclerViewAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {
            currentEnterActions.remove(position);
            actionRecyclerViewAdapter.notifyDataSetChanged();
            sendActionsChangedBroadcast(getContext(), currentEnterActions);
        }
    });
    RecyclerView recyclerViewTimerActions = (RecyclerView) rootView
            .findViewById(R.id.recyclerview_list_of_actions);
    recyclerViewTimerActions.setAdapter(actionRecyclerViewAdapter);
    StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1,
            StaggeredGridLayoutManager.VERTICAL);
    recyclerViewTimerActions.setLayoutManager(layoutManager);

    Bundle args = getArguments();
    if (args != null && args.containsKey(ConfigureGeofenceDialog.GEOFENCE_ID_KEY)) {
        long geofenceId = args.getLong(ConfigureGeofenceDialog.GEOFENCE_ID_KEY);
        initializeData(geofenceId);
    }

    sendActionsChangedBroadcast(getContext(), currentEnterActions);

    return rootView;
}

From source file:com.perm.DoomPlay.AbstractReceiver.java

private void initializeKiller() {
    IntentFilter intentFilterKiller = new IntentFilter(actionKill);
    broadcastReceiverKiller = new BroadcastReceiver() {
        @Override/*from w  ww .  j  a  va 2  s. c om*/
        public void onReceive(Context context, Intent intent) {
            if (PlayingService.serviceAlive) {
                stopService(new Intent(getBaseContext(), PlayingService.class));
                PlayingService.serviceAlive = false;
            }
            finish();
        }
    };
    registerReceiver(broadcastReceiverKiller, intentFilterKiller);
}

From source file:de.spiritcroc.ownlog.ui.view.EditTagsView.java

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();

    LocalBroadcastManager.getInstance(getContext())
            .registerReceiver(mTagBroadcastReceiver = new BroadcastReceiver() {
                @Override//w  w w .j  a  v  a 2s.com
                public void onReceive(Context context, Intent intent) {
                    Parcelable item = intent.getParcelableExtra(Constants.EXTRA_TAG_ITEM);
                    if (!(item instanceof TagItem)) {
                        Log.w(TAG, "Received invalid tag item: " + item);
                        return;
                    }
                    switch (intent.getIntExtra(Constants.EXTRA_TAG_ACTION, -1)) {
                    case Constants.TAG_ACTION_ADD:
                        onAddTagResult((TagItem) item);
                        break;
                    case Constants.TAG_ACTION_EDIT:
                        onEditTagResult((TagItem) item);
                        break;
                    case Constants.TAG_ACTION_DELETE:
                        onDeleteTagResult((TagItem) item);
                        break;
                    default:
                        Log.w(TAG, "Received unknown tag action: "
                                + intent.getIntExtra(Constants.EXTRA_TAG_ACTION, -1));
                        break;
                    }
                }
            }, new IntentFilter(Constants.EVENT_TAG_UPDATE));
}