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.remobile.batteryStatus.BatteryListener.java

/**
 * Executes the request./*from ww w  . j a v  a2 s.c o m*/
 *
 * @param action           The action to execute.
 * @param args             JSONArry of arguments for the plugin.
 * @param callbackContext    The callback context used when calling back into JavaScript.
 * @return                 True if the action was valid, false if not.
 */
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    if (action.equals("start")) {
        // We need to listen to power events to update battery status
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        if (this.receiver == null) {
            this.receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    updateBatteryInfo(intent);
                }
            };
            getReactApplicationContext().registerReceiver(this.receiver, intentFilter);
        }

        // Don't return any result now, since status results will be sent when events come in from broadcast receiver
        callbackContext.success();
        return true;
    }

    else if (action.equals("stop")) {
        removeBatteryListener();
        callbackContext.success();
        return true;
    }

    return false;
}

From source file:com.thelastcrusade.soundstream.util.BroadcastRegistrar.java

public void register(Context context) {
    //this receiver routes actions to their registered handler
    this.localReceiver = new BroadcastReceiver() {

        @Override/*from www  .  j av  a2s.  co m*/
        public void onReceive(Context context, Intent intent) {
            for (String key : localHandlerMap.keySet()) {
                if (key.equals(intent.getAction())) {
                    localHandlerMap.get(key).onReceiveAction(context, intent);
                }
            }
        }
    };

    this.globalReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            for (String key : globalHandlerMap.keySet()) {
                if (key.equals(intent.getAction())) {
                    globalHandlerMap.get(key).onReceiveAction(context, intent);
                }
            }
        }
    };

    //register the local receiver, with the assembled filter
    LocalBroadcastManager.getInstance(context).registerReceiver(localReceiver, localFilter);

    //register the global receiver, with the assembled filter
    context.registerReceiver(globalReceiver, globalFilter);

    //hold on to the registered context, for unregister
    this.registeredContext = context;
}

From source file:com.gigathinking.simpleapplock.AppLaunchDetectorService.java

@Override
public void onCreate() {
    super.onCreate();
    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mAppListData = new AppListData(getApplicationContext());
    mAppListData.init();// ww  w.j  a  v  a2 s  . co  m
    updateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (!mList.isEmpty()) {
                mList.clear();
            }
            if (!mAppMap.isEmpty()) {
                mAppMap.clear();
            }
            Cursor cursor = mAppListData.getAppListInfo();
            int count = cursor.getCount();
            for (int i = 0; i < count; ++i) {
                cursor.moveToPosition(i);
                mList.add(cursor.getString(2));
                mAppMap.put(cursor.getString(2), Boolean.valueOf(cursor.getString(3)));
                mLastOpen.put(cursor.getString(2), cursor.getInt(4));
            }
        }
    };
    mList = new ArrayList<String>();
    mAppMap = new HashMap<String, Boolean>();
    mLastOpen = new HashMap<String, Integer>();
    Cursor cursor = mAppListData.getAppListInfo();
    int count = cursor.getCount();
    for (int i = 0; i < count; ++i) {
        cursor.moveToPosition(i);
        mList.add(cursor.getString(2));
        mAppMap.put(cursor.getString(2), Boolean.valueOf(cursor.getString(3)));
        mLastOpen.put(cursor.getString(2), cursor.getInt(4));
    }
    cursor.close();
    LocalBroadcastManager.getInstance(this).registerReceiver(updateReceiver,
            new IntentFilter(AppLockApplication.UPDATE_LIST));
    new DetectAppLaunch().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.brewcrewfoo.performance.fragments.BatteryInfo.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = getActivity();/*from w  ww.ja v  a  2s  .  c om*/
    mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    batteryInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //int  health= intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0);
            //String  technology= intent.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY);
            //boolean  present= intent.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT);
            //int  rawvoltage= intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0);

            plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
            int lev = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
            int temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);

            level = lev * scale / 100;
            mbattery_percent.setText(level + "%");
            if (new File(BAT_VOLT_PATH).exists()) {
                int volt = Integer.parseInt(Helpers.readOneLine(BAT_VOLT_PATH));
                if (volt > 5000)
                    volt = (int) Math.round(volt / 1000.0);// in microvolts
                mbattery_volt.setText(volt + " mV");
            }
            switch ((int) Math.ceil(level / 20.0)) {
            case 0:
                mBattIcon.setImageResource(R.drawable.battery_0);
                break;
            case 1:
                mBattIcon.setImageResource(R.drawable.battery_1);
                break;
            case 2:
                mBattIcon.setImageResource(R.drawable.battery_2);
                break;
            case 3:
                mBattIcon.setImageResource(R.drawable.battery_3);
                break;
            case 4:
                mBattIcon.setImageResource(R.drawable.battery_4);
                break;
            case 5:
                mBattIcon.setImageResource(R.drawable.battery_5);
                break;
            }
            mbattery_status.setText(
                    (temperature / 10) + "C  " + getResources().getStringArray(R.array.batt_status)[status]);
        }
    };
    //getActivity().registerReceiver(batteryInfoReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED) );
    setRetainInstance(true);
    setHasOptionsMenu(true);

}

From source file:curiosamente.com.app.activities.main.MainActivity.java

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

    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    MainFragment mainFragment = new MainFragment();
    fragmentTransaction.add(R.id.main_layout, mainFragment);
    fragmentTransaction.commit();//from   w ww  .  j  a v a2  s.c  o  m

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

            Bar[] bars = (Bar[]) intent.getExtras().get(HttpService.RETURNOBJECT_EXTRA_PROPERTY);
            //                FragmentManager fm = getFragmentManager();
            //                FragmentTransaction fragmentTransaction = fm.beginTransaction();
        }
    };

    mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_main);
    mDrawerTextView = (TextView) findViewById(R.id.facebook_name_text);
    mDrawerLogoutButton = (Button) mDrawerLayout.findViewById(R.id.facebook_logout_button);
    mDrawerImage = (ImageView) findViewById(R.id.profileImage);

    Intent intent = new Intent(this, HttpService.class);
    intent.putExtra(HttpService.URL_EXTRA_PROPERTY, "http://192.168.0.13:8080/bar");
    intent.putExtra(HttpService.CLASS_EXTRA_PROPERTY, Bar[].class);
    startService(intent);

    initDrawer();
}

From source file:com.mobile.lapa.waitandsee.MainActivity.java

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

    mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override/*from w w  w  .j  a va2s  . com*/
        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) {
                mMessageTextView.setText(getString(R.string.token_error_message));
            }
        }
    };

    mMessageTextView = (TextView) findViewById(R.id.messageTextView);
    mTitleTextView = (TextView) findViewById(R.id.titleTextView);
    mUserNameEditText = (EditText) findViewById(R.id.userNameEditText);
    mSubmitButton = (Button) findViewById(R.id.submitButton);

    mUserNameEditText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                mSubmitButton.performClick();
                return true;
            }
            return false;
        }
    });

    if (this.textToSpeech == null) {
        textToSpeech = new TextToSpeech(this.getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    textToSpeech.setLanguage(Locale.ENGLISH); //getDefault());
                }
            }
        });
    }

    Bundle b = getIntent().getExtras();
    String title = "";
    String message = "";
    if (b != null) {
        title = b.getString("TITLE_KEY");
        message = b.getString("MESSAGE_KEY");
    }

    if (title == "" && message == "") { //(b == null) {
        mTitleTextView.setText(getString(R.string.welcome_title));
        mMessageTextView.setText(getString(R.string.welcome_message));
    } else {
        mTitleTextView.setText(title);
        mMessageTextView.setText(message);
        playSound(title);
    }

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
    // ------- User name ------------
    settings = getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
    userName = settings.getString("USER_NAME", "");
    if (userName != "") {
        // user name already set
        hideUserFields();
    }
    setUserTitle();
}

From source file:com.veniosg.dir.mvvm.model.storage.access.SafStorageAccessManager.java

@Override
public void requestWriteAccess(@NonNull final File fileInStorage,
        @NonNull final AccessPermissionListener listener) {
    final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
    localBroadcastManager.registerReceiver(new BroadcastReceiver() {
        @Override//from w w  w  .java2  s .  co m
        public void onReceive(Context context, Intent intent) {
            // We're assuming broadcast will happen in onDestroy(), and only once, regardless of SAF result
            localBroadcastManager.unregisterReceiver(this);

            if (hasWriteAccess(fileInStorage)) {
                listener.granted();
            } else {
                boolean granted = intent.getBooleanExtra(EXTRA_STORAGE_ACCESS_GRANTED, false);

                if (!granted) {
                    listener.denied();
                } else {
                    listener.error();
                }
            }
        }
    }, new IntentFilter(ACTION_STORAGE_ACCESS_RESULT));
    Intent safPromptIntent = new Intent(context, SafPromptActivity.class);
    safPromptIntent.addFlags(FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(safPromptIntent);
}

From source file:com.example.todd.mrqsample.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mapp = (Myapplication) getApplication();
    mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override/*from   w w  w .j a  v a 2  s  .c o m*/
        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));
                try {
                    Log.d("MRQ_MRQMainActivity", mrqSdk.getGcmRegistrationId().toString());
                } catch (Exception e) {
                    Log.d("MRQ_MRQMainActivity", e.toString());
                }
                setContext();
            } else {
                mInformationTextView.setText(getString(R.string.token_error_message));
            }
        }
    };
    mInformationTextView = (TextView) findViewById(R.id.informationTextView);

    // Registering BroadcastReceiver
    registerReceiver();

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

    //mrqSdk.
    //mrqSdk.refresh();
}

From source file:eu.power_switch.gui.activity.RoomsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // set Theme before anything else in onCreate
    ThemeHelper.applyTheme(this);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rooms);

    // allow always-on screen
    setAmbientEnabled();// w w  w.  j  a  v  a2 s  . co  m

    dataApiHandler = new DataApiHandler(getApplicationContext());

    // 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("MainActivity", "received intent: " + intent.getAction());

            ArrayList<Room> rooms = (ArrayList<Room>) intent.getSerializableExtra(ListenerService.ROOM_DATA);
            replaceRoomList(rooms);

            refreshUI();
        }
    };

    final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
        @Override
        public void onLayoutInflated(WatchViewStub stub) {

            relativeLayoutAmbientMode = (RelativeLayout) findViewById(R.id.relativeLayout_ambientMode);

            roomsRecyclerView = (RecyclerView) findViewById(R.id.rooms_recyclerView);
            roomsRecyclerViewAdapter = new RoomRecyclerViewAdapter(stub.getContext(), roomsRecyclerView,
                    roomList, dataApiHandler);
            roomsRecyclerView.setAdapter(roomsRecyclerViewAdapter);

            SnappingLinearLayoutManager layoutManager = new SnappingLinearLayoutManager(getApplicationContext(),
                    LinearLayoutManager.VERTICAL, false);
            roomsRecyclerView.setLayoutManager(layoutManager);
        }
    });
}

From source file:com.nadmm.airports.wx.AirSigmetFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);/*  w  w  w  .  java  2  s  .  c  o m*/

    mFilter = new IntentFilter();
    mFilter.addAction(mAction);

    mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(mAction)) {
                String type = intent.getStringExtra(NoaaService.TYPE);
                if (type.equals(NoaaService.TYPE_TEXT)) {
                    showAirSigmetText(intent);
                }
            }
        }
    };
}