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:ack.me.truconnectandroiddemo.DeviceInfoActivity.java

private void initBroadcastReceiver() {
    mBroadcastReceiver = new BroadcastReceiver() {
        @Override//ww  w.  ja v  a  2 s  .  c  o  m
        public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent
            String action = intent.getAction();

            switch (action) {
            case TruconnectService.ACTION_COMMAND_SENT:
                String command = TruconnectService.getCommand(intent).toString();
                Log.d(TAG, "Command " + command + " sent");
                break;

            case TruconnectService.ACTION_COMMAND_RESULT:
                handleCommandResponse(intent);
                break;

            case TruconnectService.ACTION_ERROR:
                TruconnectErrorCode errorCode = TruconnectService.getErrorCode(intent);
                //handle errors
                break;

            case TruconnectService.ACTION_DISCONNECTED:
                mDisconnectDialog.dismiss();
                finish();
                break;
            }
        }
    };
}

From source file:com.github.caifatcmd.VolumeService.java

@Override
public void onCreate() {
    pref = getApplicationContext().getSharedPreferences(PREF_NAME, Context.MODE_MULTI_PROCESS);
    //pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String atcmdBinaryName = getApplicationContext().getResources().getText(R.string.atcmd_binary).toString();
    if ((new File("/system/bin/caifatcmd")).isFile())
        atcmdBinary = "/system/bin/caifatcmd";
    else if ((new File(getApplicationInfo().dataDir + "/lib/" + atcmdBinaryName)).isFile())
        atcmdBinary = getApplicationInfo().dataDir + "/lib/" + atcmdBinaryName;

    // Get current volume
    Integer retVal = 0; // = runATCmd(0);
    currentVolume = MAX_VOL; // - retVal + 1;
    gotoVolume = pref.getInt(CURR_VOL_KEY, currentVolume);
    Log.d("CallVolService", "Stored volume at " + gotoVolume);

    if (gotoVolume != currentVolume)
        retVal = runATCmd(gotoVolume);/*ww w . j  a v a2  s .c  o m*/

    if (retVal >= 0)
        currentVolume = gotoVolume;
    pref.edit().putInt(CURR_VOL_KEY, currentVolume).commit();
    //pref.edit().commit();

    //serviceActive = true;
    //stopSelf();

    super.onCreate();
    //return Service.START_NOT_STICKY;

    broadcaster = LocalBroadcastManager.getInstance(this);
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateVolumeData();
        }
    };
}

From source file:com.klinker.android.twitter.ui.tweet_viewer.TweetPager.java

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

    overridePendingTransition(R.anim.activity_slide_up, R.anim.activity_slide_down);

    try {/*from  w ww.j a v  a 2s. c  om*/
        getWindow().requestFeature(Window.FEATURE_PROGRESS);
    } catch (Exception e) {

    }

    context = this;
    settings = AppSettings.getInstance(this);

    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception ex) {
        // Ignore
    }

    getFromIntent();

    // methods for advancing windowed
    boolean settingsVal = settings.advanceWindowed;
    boolean fromWidget = getIntent().getBooleanExtra("from_widget", false);
    final boolean youtube;
    if (webpage != null && linkString != null) {
        youtube = webpage.contains("youtu") || linkString.contains("youtu");
    } else {
        youtube = true;
    }

    // cases: (youtube will ALWAYS be full screen...)
    // from widget
    // the user set the preference to advance windowed
    // has a webview and want to advance windowed
    if (fromWidget || settingsVal) {
        setUpWindow(youtube);
    }

    setUpTheme();

    int currentOrientation = getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
    }

    if (getIntent().getBooleanExtra("clicked_youtube", false)) {
        IntentFilter i = new IntentFilter("com.klinker.android.twitter.YOUTUBE_READY");
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                TweetYouTubeFragment.resume();

                context.unregisterReceiver(this);
            }
        }, i);
    }

    setContentView(R.layout.tweet_pager);
    pager = (ViewPager) findViewById(R.id.pager);
    mSectionsPagerAdapter = new TweetPagerAdapter(getFragmentManager(), context, name, screenName, tweet, time,
            retweeter, webpage, proPic, tweetId, picture, users, hashtags, otherLinks, isMyTweet, isMyRetweet);
    pager.setAdapter(mSectionsPagerAdapter);
    pager.setOffscreenPageLimit(5);

    final int numberOfPages = mSectionsPagerAdapter.getCount();

    pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i2) {

        }

        @Override
        public void onPageSelected(int i) {
            if (youtube) {
                try {
                    switch (numberOfPages) {
                    case 3:
                    case 4:
                        if (i != 0) {
                            TweetYouTubeFragment.pause();
                        } else {
                            TweetYouTubeFragment.resume();
                        }
                        break;
                    case 5:
                        if (i != 1) {
                            TweetYouTubeFragment.pause();
                        } else {
                            TweetYouTubeFragment.resume();
                        }
                        break;
                    }
                } catch (Exception e) {

                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });

    switch (numberOfPages) {
    case 2:
        if (settings.pageToOpen == AppSettings.PAGE_CONVO) {
            pager.setCurrentItem(1);
        } else {
            pager.setCurrentItem(0);
        }
        break;
    case 3:
        if (mSectionsPagerAdapter.getHasWebpage()) {
            switch (settings.pageToOpen) {
            case AppSettings.PAGE_CONVO:
                pager.setCurrentItem(2);
                break;
            case AppSettings.PAGE_WEB:
                pager.setCurrentItem(0);
                break;
            default:
                pager.setCurrentItem(1);
                break;
            }
        } else { // no web page
            switch (settings.pageToOpen) {
            case AppSettings.PAGE_CONVO:
                pager.setCurrentItem(2);
                break;
            default:
                pager.setCurrentItem(1);
                break;
            }
        }
        break;
    case 4: // webpage and youtube
        switch (settings.pageToOpen) {
        case AppSettings.PAGE_CONVO:
            pager.setCurrentItem(3);
            break;
        case AppSettings.PAGE_WEB:
            pager.setCurrentItem(1);
            break;
        default:
            pager.setCurrentItem(0);
            break;
        }
        break;
    }

    if (getIntent().getBooleanExtra("clicked_youtube", false)) {
        pager.setCurrentItem(0);
    }

    if (settings.addonTheme) {
        PagerTitleStrip strip = (PagerTitleStrip) findViewById(R.id.pager_title_strip);
        strip.setBackgroundColor(settings.pagerTitleInt);

        if (!settings.showTitleStrip) {
            strip.setVisibility(View.GONE);
        }
    }

}

From source file:com.google.codelab.networkmanager.MainActivity.java

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

    mTaskAdapter = new TaskAdapter(new ArrayList<TaskItem>());
    mGcmNetworkManager = GcmNetworkManager.getInstance(this);

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    mRecyclerView.setLayoutManager(linearLayoutManager);
    mRecyclerView.setAdapter(mTaskAdapter);
    Button bestTimeButton = (Button) findViewById(R.id.bestTimeButton);
    bestTimeButton.setOnClickListener(new View.OnClickListener() {
        @Override//w ww . j  a va2 s. c  o  m
        public void onClick(View view) {
            String taskId = TASK_ID_PREFIX + Calendar.getInstance().getTimeInMillis();
            Log.d(TAG, "Scheduling oneoff task. " + taskId);
            TaskItem taskItem = new TaskItem(taskId, TaskItem.ONEOFF_TASK, TaskItem.PENDING_STATUS);
            new AddTask(view.getContext()).execute(taskItem);
        }
    });

    Button nowButton = (Button) findViewById(R.id.nowButton);
    nowButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String taskId = TASK_ID_PREFIX + Calendar.getInstance().getTimeInMillis();
            Log.d(TAG, "Creating a Now Task. " + taskId);
            TaskItem taskItem = new TaskItem(taskId, TaskItem.NOW_TASK, TaskItem.PENDING_STATUS);
            new AddTask(view.getContext()).execute(taskItem);
        }
    });

    mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
    mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String taskId = intent.getStringExtra(CodelabUtil.TASK_ID);
            String status = intent.getStringExtra(CodelabUtil.TASK_STATUS);

            mTaskAdapter.updateTaskItemStatus(taskId, status);
        }
    };
}

From source file:com.slushpupie.deskclock.DeskClock.java

public DeskClock() {
    super();/*from  w  ww.  java 2  s .c o m*/
    // determine if multitouch is really supported
    try {
        getXMethod = MotionEvent.class.getMethod("getX", new Class[] { int.class });
        getYMethod = MotionEvent.class.getMethod("getY", new Class[] { int.class });
        supportMultiTouch = true;
    } catch (NoSuchMethodException nsme) {
        supportMultiTouch = false;
    }

    intentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (Intent.ACTION_DOCK_EVENT.equals(action)) {
                int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE, 0);
                switch (dockState) {
                case Intent.EXTRA_DOCK_STATE_UNDOCKED:
                    Log.d(LOG_TAG, "received EXTRA_DOCK_STATE_UNDOCKED");
                    if (prefsUndockExit)
                        finish();
                    else
                        Log.d(LOG_TAG, "Ignoring...");
                    break;
                case Intent.EXTRA_DOCK_STATE_DESK:
                    Log.d(LOG_TAG, "received EXTRA_DOCK_STATE_DESK");
                    break;
                }
            }
            if (Intent.ACTION_TIME_TICK.equals(action)) {
                updateTime();
            }
        }
    };
}

From source file:com.hedgehog.smdb.ActionBarControlScrollViewActivity.java

private void repeat() {
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override/*w w  w .  j a  v a  2s  .c  om*/
        public void onReceive(Context context, Intent intent) {
            showNotification();
        }
    };

    this.registerReceiver(receiver, new IntentFilter("TecxiDriverCheckingForConfirmedBids"));
    PendingIntent pintent = PendingIntent.getBroadcast(this, 0,
            new Intent("TecxiDriverCheckingForConfirmedBids"), 0);
    AlarmManager manager = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
    manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, 1000 * 60 * 30, pintent);
}

From source file:com.cuddlesoft.nori.test.database.APISettingsDatabaseTest.java

/** Test if the database sends a Broadcast to the {@link android.support.v4.content.LocalBroadcastManager} when the data is changed. */
public void testUpdateBroadcast() throws Throwable {
    // Create a lock that waits for the broadcast to be received in the background.
    final CountDownLatch lock = new CountDownLatch(3);

    runTestOnUiThread(new Runnable() {
        @Override/*from  ww w  .j ava  2  s .c  o m*/
        public void run() {
            // Register BroadcastReceiver.
            LocalBroadcastManager.getInstance(context).registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    lock.countDown(); // Should receive 3 Broadcasts, one for each database operation.
                    if (lock.getCount() == 0) {
                        // Unregister broadcast receiver.
                        LocalBroadcastManager.getInstance(context).unregisterReceiver(this);
                    }
                }
            }, new IntentFilter(APISettingsDatabase.BROADCAST_UPDATE));
            // Trigger database change broadcasts.
            APISettingsDatabase database = new APISettingsDatabase(context);
            long rowID = database.insert(new SearchClient.Settings(SearchClient.Settings.APIType.DANBOORU,
                    "Danbooru", "http://danbooru.donmai.us"));
            database.update(rowID, new SearchClient.Settings(SearchClient.Settings.APIType.DANBOORU_LEGACY,
                    "Danbooru", "http://danbooru.donmai.us"));
            database.delete(rowID);
            database.close();
        }
    });

    // Wait 10 seconds for the test to complete.
    lock.await(10, TimeUnit.SECONDS);
    assertThat(lock.getCount()).isEqualTo(0);
}

From source file:eu.power_switch.gui.fragment.configure_gateway.ConfigureGatewayDialogPage2Fragment.java

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

    recyclerViewSsids = (RecyclerView) rootView.findViewById(R.id.recyclerView_ssids);
    ssidRecyclerViewAdapter = new SsidRecyclerViewAdapter(getActivity(), ssids);
    recyclerViewSsids.setAdapter(ssidRecyclerViewAdapter);
    ssidRecyclerViewAdapter.setOnDeleteClickListener(new SsidRecyclerViewAdapter.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 {
                                ssids.remove(position);
                                ssidRecyclerViewAdapter.notifyDataSetChanged();
                                notifyConfigurationChanged();
                            } catch (Exception e) {
                                StatusMessageHandler.showErrorMessage(getActivity(), e);
                            }
                        }
                    }).setNeutralButton(android.R.string.cancel, null).show();
        }
    });
    StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1,
            StaggeredGridLayoutManager.VERTICAL);
    recyclerViewSsids.setLayoutManager(layoutManager);

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

    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (LocalBroadcastConstants.INTENT_GATEWAY_SSID_ADDED.equals(intent.getAction())) {
                ArrayList<String> newSsids = intent.getStringArrayListExtra(AddSsidDialog.KEY_SSID);
                ssids.addAll(newSsids);
                ssidRecyclerViewAdapter.notifyDataSetChanged();
            }

            if (LocalBroadcastConstants.INTENT_GATEWAY_SETUP_CHANGED.equals(intent.getAction())) {
                currentName = intent.getStringExtra("name");
                currentModel = intent.getStringExtra("model");
                currentLocalAddress = intent.getStringExtra("localAddress");
                currentLocalPort = intent.getIntExtra("localPort", -1);
                currentWanAddress = intent.getStringExtra("wanAddress");
                currentWanPort = intent.getIntExtra("wanPort", -1);
            }

            notifyConfigurationChanged();
        }
    };

    Bundle args = getArguments();
    if (args != null && args.containsKey(ConfigureGatewayDialog.GATEWAY_ID_KEY)) {
        gatewayId = args.getLong(ConfigureGatewayDialog.GATEWAY_ID_KEY);
        initializeGatewayData(gatewayId);
    }

    return rootView;
}

From source file:io.github.tjg1.nori.test.database.APISettingsDatabaseTest.java

/** Test if the database sends a Broadcast to the {@link android.support.v4.content.LocalBroadcastManager} when the data is changed. */
public void testUpdateBroadcast() throws Throwable {
    // Create a lock that waits for the broadcast to be received in the background.
    final CountDownLatch lock = new CountDownLatch(3);

    runTestOnUiThread(new Runnable() {
        @Override/*  ww  w  .  java  2  s  .  com*/
        public void run() {
            // Register BroadcastReceiver.
            LocalBroadcastManager.getInstance(context).registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    lock.countDown(); // Should receive 3 Broadcasts, one for each database operation.
                    if (lock.getCount() == 0) {
                        // Unregister broadcast receiver.
                        LocalBroadcastManager.getInstance(context).unregisterReceiver(this);
                    }
                }
            }, new IntentFilter(APISettingsDatabase.BROADCAST_UPDATE));
            // Trigger database change broadcasts.
            APISettingsDatabase database = new APISettingsDatabase(context);
            long rowID = database.insert(new SearchClient.Settings(SearchClient.Settings.APIType.DANBOARD,
                    "Danbooru", "http://danbooru.donmai.us"));
            database.update(rowID, new SearchClient.Settings(SearchClient.Settings.APIType.DANBOARD_LEGACY,
                    "Danbooru", "http://danbooru.donmai.us"));
            database.delete(rowID);
            database.close();
        }
    });

    // Wait 10 seconds for the test to complete.
    lock.await(10, TimeUnit.SECONDS);
    assertThat(lock.getCount()).isEqualTo(0);
}

From source file:eu.power_switch.gui.fragment.geofences.CustomGeofencesFragment.java

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

    setHasOptionsMenu(true);//from w w  w  .j av  a2 s .  co m

    geofenceApiHandler = new GeofenceApiHandler(getActivity());

    recyclerViewGeofences = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    geofenceRecyclerViewAdapter = new GeofenceRecyclerViewAdapter(getActivity(), geofences, geofenceApiHandler);
    recyclerViewGeofences.setAdapter(geofenceRecyclerViewAdapter);
    StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(getSpanCount(),
            StaggeredGridLayoutManager.VERTICAL);
    recyclerViewGeofences.setLayoutManager(layoutManager);

    final RecyclerViewFragment recyclerViewFragment = this;
    geofenceRecyclerViewAdapter
            .setOnItemLongClickListener(new GeofenceRecyclerViewAdapter.OnItemLongClickListener() {
                @Override
                public void onItemLongClick(View itemView, int position) {
                    final Geofence geofence = geofences.get(position);

                    ConfigureGeofenceDialog configureGeofenceDialog = ConfigureGeofenceDialog
                            .newInstance(geofence.getId());
                    configureGeofenceDialog.setTargetFragment(recyclerViewFragment, 0);
                    configureGeofenceDialog.show(getFragmentManager(), null);
                }
            });

    fab = (FloatingActionButton) rootView.findViewById(R.id.add_fab);
    fab.setImageDrawable(IconicsHelper.getAddIcon(getActivity(),
            ContextCompat.getColor(getActivity(), android.R.color.white)));
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!PermissionHelper.isLocationPermissionAvailable(getContext())) {
                new AlertDialog.Builder(getContext()).setTitle(R.string.missing_permission)
                        .setMessage(R.string.missing_location_permission).setNeutralButton(R.string.close, null)
                        .show();
                return;
            }

            ConfigureGeofenceDialog configureGeofenceDialog = new ConfigureGeofenceDialog();
            configureGeofenceDialog.setTargetFragment(recyclerViewFragment, 0);
            configureGeofenceDialog.show(getFragmentManager(), 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());

            switch (intent.getAction()) {
            case LocalBroadcastConstants.INTENT_CUSTOM_GEOFENCE_CHANGED:
                refreshGeofences();
                break;
            case LocalBroadcastConstants.INTENT_PERMISSION_CHANGED:
                int permissionRequestCode = intent.getIntExtra(PermissionConstants.KEY_REQUEST_CODE, 0);
                int[] result = intent.getIntArrayExtra(PermissionConstants.KEY_RESULTS);

                if (permissionRequestCode == PermissionConstants.REQUEST_CODE_LOCATION_PERMISSION) {
                    if (result[0] == PackageManager.PERMISSION_GRANTED) {
                        StatusMessageHandler.showInfoMessage(getRecyclerView(), R.string.permission_granted,
                                Snackbar.LENGTH_SHORT);

                        sendCustomGeofencesChangedBroadcast(context);
                    } else {
                        StatusMessageHandler.showPermissionMissingMessage(getActivity(), getRecyclerView(),
                                Manifest.permission.ACCESS_FINE_LOCATION);
                    }
                }
                break;
            }

        }
    };
}