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.supremainc.biostar2.guide.GuideActivity.java

private void registerBroadcast() {
    if (mClearReceiver == null) {
        mClearReceiver = new BroadcastReceiver() {
            @Override//  w  w w. ja  va2s .  c  o m
            public void onReceive(Context context, Intent intent) {
                if (isFinishing()) {
                    return;
                }
                final String action = intent.getAction();
                if (BuildConfig.DEBUG) {
                    Log.e(TAG, "receive:" + action);
                }
                if (action.equals(Setting.BROADCAST_ALL_CLEAR)) {
                    finish();
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Setting.BROADCAST_ALL_CLEAR);
        LocalBroadcastManager.getInstance(this).registerReceiver(mClearReceiver, intentFilter);
    }
}

From source file:com.google.firebase.quickstart.fcm.MainActivity.java

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

    // If a notification message is tapped, any data accompanying the notification
    // message is available in the intent extras. In this sample the launcher
    // intent is fired when the notification is tapped, so any accompanying data would
    // be handled here. If you want a different intent fired, set the click_action
    // field of the notification message to the desired intent. The launcher intent
    // is used when no click_action is specified.
    ///*from w  w  w.  ja v  a  2  s .c o m*/
    // Handle possible data accompanying notification message.
    // [START handle_data_extras]
    Intent intent = getIntent();
    logIntent(intent, "FIRST INTENT RECEIVED");
    updateDataTextView(intent);
    // [END handle_data_extras]

    LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT|Intent.FLAG_ACTIVITY_SINGLE_TOP);
            //startActivity(intent);
            updateDataTextView(intent);
        }
    }, new IntentFilter(MyFirebaseMessagingService.ACTION_DATA_BROADCAST));

    Button subscribeButton = (Button) findViewById(R.id.subscribeButton);
    subscribeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // [START subscribe_topics]
            FirebaseMessaging.getInstance().subscribeToTopic(TOPIC);
            // [END subscribe_topics]

            // Log and toast
            String msg = getString(R.string.msg_subscribed);
            Log.d(TAG, msg);
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

    Button logTokenButton = (Button) findViewById(R.id.logTokenButton);
    logTokenButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Get token
            String token = FirebaseInstanceId.getInstance().getToken();

            // Log and toast
            String msg = getString(R.string.msg_token_fmt, token);
            Log.d(TAG, msg);
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

    Button resetDataButton = (Button) findViewById(R.id.resetDataTextView);
    resetDataButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView dataTextView = (TextView) findViewById(R.id.dataTextView);
            dataTextView.setText(R.string.data_msg);
        }
    });

}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_reset);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    mDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
    mDialog.setIndeterminate(true);/*w w  w.  j a v  a 2  s. c  o m*/
    prefs = PreferenceManager.getDefaultSharedPreferences(this);

    mResetReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            prefs.edit().putString(AppLockApplication.LOCKTYPE, AppLockApplication.LOCKTYPE_PIN).commit();
            prefs.edit()
                    .putString(AppLockApplication.PASSWORD, intent.getStringExtra(AppLockApplication.PASSWORD))
                    .commit();
            Toast.makeText(context, getString(R.string.pin_reset), Toast.LENGTH_LONG).show();
            startActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
            //startActivity(new Intent(ResetUnlockMethod.this,UnlockWithPIN.class).putExtra("test","test"));
            finish();
        }
    };
    LocalBroadcastManager.getInstance(this).registerReceiver(mResetReceiver,
            new IntentFilter(AppLockApplication.RESET_UNLOCK));

    if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean(getString(R.string.register_complete),
            false)) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getString(R.string.reset_register_device));
        builder.setTitle(getString(R.string.info));
        builder.setPositiveButton(getString(R.string.register), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                new Register().execute();
                if (mDialog != null) {
                    mDialog.setMessage(getString(R.string.register_ongoing));
                    mDialog.show();
                }
                dialog.dismiss();
            }
        });
        builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        builder.create().show();
    } else {
        if (mDialog != null) {
            mDialog.setMessage(getString(R.string.connect_to_server));
            mDialog.show();
        }
        new DoRequestReset().execute();
    }
}

From source file:com.redirectapps.tvkill.RepetitiveModeService.java

@Override
protected void onHandleIntent(Intent intent) {

    //Set the running-boolean in MainActivity to true
    MainActivity.repetitiveModeRunning = true;

    //Display a Notification while this Service is running

    //Build the Notification
    NotificationBuilder = new NotificationCompat.Builder(this);
    NotificationBuilder.setOngoing(true);
    NotificationBuilder.setAutoCancel(false);
    NotificationBuilder.setPriority(Notification.PRIORITY_MAX);
    //NotificationBuilder.setCategory(Notification.CATEGORY_SERVICE);
    NotificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    NotificationBuilder.setSmallIcon(R.drawable.ic_power_settings_new_white_48dp);
    NotificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
    NotificationBuilder.setContentTitle(getString(R.string.mode_running));

    //Create a BroadcastReceiver that stops the service when called
    stopReceiver = new BroadcastReceiver() {
        @Override//w  ww  .  ja v  a 2 s .  c  o m
        public void onReceive(Context context, Intent intent) {
            stopSelf();
        }
    };
    registerReceiver(stopReceiver, new IntentFilter("stop"));

    //Add a Action to the Notification that calls the BroadcastReceiver
    Intent receiverIntent = new Intent("stop");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, receiverIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationBuilder.addAction(R.drawable.ic_clear_black_48dp, getString(R.string.stop), pendingIntent);

    //Display the notification
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mNotificationManager.notify(NotificationID, NotificationBuilder.build());

    //Notify the user that the service has started
    Toast.makeText(getApplicationContext(), R.string.toast_mode_started, Toast.LENGTH_LONG).show();

    //Send Patterns until this service is stopped
    if (selectedBrand == 0)
        while (run) {
            //Send Patterns for all Brands
            Brand.killAll(this);
        }
    else {
        BrandContainer.getAllBrands();
        Brand b = BrandContainer.getAllBrands()[selectedBrand - 1];
        while (run) {
            //Send the patterns of the selected brand
            b.kill(this);
        }
    }

}

From source file:com.phonegap.BatteryListener.java

/**
 * Executes the request and returns PluginResult.
 * /*from ww  w  . ja v  a 2  s. c om*/
 * @param action        The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackId    The callback id used when calling back into JavaScript.
 * @return              A PluginResult object with a status and message.
 */
public PluginResult execute(String action, JSONArray args, String callbackId) {
    PluginResult.Status status = PluginResult.Status.INVALID_ACTION;
    String result = "Unsupported Operation: " + action;

    if (action.equals("start")) {
        if (this.batteryCallbackId != null) {
            return new PluginResult(PluginResult.Status.ERROR, "Battery listener already running.");
        }
        this.batteryCallbackId = callbackId;

        // 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);
                }
            };
            ctx.registerReceiver(this.receiver, intentFilter);
        }

        // Don't return any result now, since status results will be sent when events come in from broadcast receiver 
        PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
        pluginResult.setKeepCallback(true);
        return pluginResult;
    }

    else if (action.equals("stop")) {
        removeBatteryListener();
        this.sendUpdate(new JSONObject(), false); // release status callback in JS side
        this.batteryCallbackId = null;
        return new PluginResult(PluginResult.Status.OK);
    }

    return new PluginResult(status, result);
}

From source file:com.oodles.smslistener.SmsListenerModule.java

void setupIntentReceivers() {
    Log.d(LCAT, "inside setupIntentReceivers");
    Activity currentActivity = TiApplication.getInstance().getCurrentActivity();

    //let's register broadcast receivers
    BroadcastReceiver smsReceiver = new BroadcastReceiver() {
        @Override/*from w  w  w . j a  va2 s  .  co m*/
        public void onReceive(Context context, Intent intent) {
            Log.d(LCAT, "inside onReceive");
            KrollDict event;
            switch (getResultCode()) {
            case Activity.RESULT_OK:

                final Bundle bundle = intent.getExtras();
                try {
                    if (bundle != null) {
                        final Object[] pdusObj = (Object[]) bundle.get("pdus");
                        for (int i = 0; i < pdusObj.length; i++) {
                            SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                            String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                            senderNum = phoneNumber;
                            message = currentMessage.getDisplayMessageBody();
                        }
                    }
                } catch (Exception e) {
                    Log.e("SmsReceiver", "Exception smsReceiver" + e);
                }
                event = createEventObject(true, RECEIVED, message, senderNum);
                Log.d(LCAT, "message Received");
                fireEvent("complete", event);
                break;
            default:
                event = createEventObject(false, FAILED, "Message delivery failed", "");
                Log.d(LCAT, "message receiving failure");
                fireEvent("complete", event);
                break;
            }
        }
    };

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.setPriority(1000);
    intentFilter.addAction(MESSAGE_RECEIVED);
    //---when the SMS has been Received---
    currentActivity.registerReceiver(smsReceiver, intentFilter);
}

From source file:com.actionbarsherlock.sample.demos.content.LocalServiceBroadcaster.java

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

    setContentView(R.layout.local_service_broadcaster);

    // This is where we print the data we get back.
    final TextView callbackData = (TextView) findViewById(R.id.callback);

    // Put in some initial text.
    callbackData.setText("No broadcast received yet");

    // We use this to send broadcasts within our local process.
    mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

    // We are going to watch for interesting local broadcasts.
    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_STARTED);/* w w  w .  ja  v  a 2s . c  o  m*/
    filter.addAction(ACTION_UPDATE);
    filter.addAction(ACTION_STOPPED);
    mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_STARTED)) {
                callbackData.setText("STARTED");
            } else if (intent.getAction().equals(ACTION_UPDATE)) {
                callbackData.setText("Got update: " + intent.getIntExtra("value", 0));
            } else if (intent.getAction().equals(ACTION_STOPPED)) {
                callbackData.setText("STOPPED");
            }
        }
    };
    mLocalBroadcastManager.registerReceiver(mReceiver, filter);

    // Watch for button clicks.
    Button button = (Button) findViewById(R.id.start);
    button.setOnClickListener(mStartListener);
    button = (Button) findViewById(R.id.stop);
    button.setOnClickListener(mStopListener);
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(false);//from  ww  w.  j  a  va2  s  .c  om

    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_IMAGE)) {
                    showWxMap(intent);
                }
            }
        }
    };

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

From source file:gcm.play.android.samples.com.gcm.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = getIntent();//from w ww  . j  a  v  a2  s  .  co m
    String mode = intent.getStringExtra("mode");
    Toast.makeText(getApplicationContext(), mode, 2);
    mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
    mInformationTextView = (TextView) findViewById(R.id.informationTextView);
    if (mode == null) {
        startActivity(new Intent(this, Topics.class));
        return;
    }
    if (mode.equals("register")) {
        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) {
                    String st = getString(R.string.gcm_send_message);
                    StringBuilder sb = new StringBuilder();
                    String[] topics = RegistrationIntentService.getTopics();
                    for (int i = 0; i < topics.length; i++)
                        sb.append(topics[i] + ", ");

                    mInformationTextView.setText(
                            st + " Currently listening to " + sb.toString().substring(0, sb.length() - 2));
                } else {
                    mInformationTextView.setText(getString(R.string.token_error_message));
                }
            }
        };

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

            } catch (Exception exp) {

            }

        }
    } else {
        mInformationTextView.setText("Unregistering in progress....");
        mUnRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.e("MAIN", "Boardcast Received");
                mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
                StringBuilder sb = new StringBuilder();
                String[] topics = UnRegisterIntentService.getTopics();
                for (int i = 0; i < topics.length; i++)
                    sb.append(topics[i] + ", ");
                String removedTopics = sb.toString().substring(0, sb.length() - 2);
                String[] RegTopics = RegistrationIntentService.getTopics();
                String[] NewTopics = new String[RegTopics.length - topics.length];
                Log.d("UnRegister", "Array Length: " + (RegTopics.length - topics.length));
                String cTopics = null;
                if (NewTopics.length > 0) {
                    int z = 0;
                    for (int i = 0; i < RegTopics.length; i++) {
                        Boolean found = false;
                        for (int j = 0; j < topics.length; j++) {

                            if (topics[j].equals(RegTopics[i]))
                                found = true;
                        }
                        if (!found) {
                            NewTopics[z] = RegTopics[i];
                            z++;
                        }
                    }
                    sb = new StringBuilder();
                    for (int i = 0; i < NewTopics.length; i++)
                        sb.append(NewTopics[i] + ", ");
                    cTopics = sb.toString().substring(0, sb.length() - 2);
                }
                if (cTopics == null)
                    cTopics = "'  '";
                RegistrationIntentService.setTopics(NewTopics, false);
                try {
                    FileOutputStream fos = openFileOutput("topics.txt", Context.MODE_PRIVATE);
                    fos.write(cTopics.replaceAll(", ", ",").getBytes());
                    fos.close();
                } catch (Exception exp) {
                }
                mInformationTextView.setText("Unregistered Succesfully from " + removedTopics
                        + ". Currently Listening to " + cTopics);

            }
        };
        Log.i("Main:", "Starting unregisteration Intent");
        Intent unregintent = new Intent(this, UnRegisterIntentService.class);
        startService(unregintent);
    }
}

From source file:inforuh.eventfinder.ui.fragment.PagerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);

    category = getArguments().getString("category");
    TextView emptyView = (TextView) view.findViewById(R.id.empty_view);
    listAdapter = new EventAdapter(getActivity(), this, emptyView);

    RecyclerView rv = (RecyclerView) view.findViewById(R.id.event_list);
    rv.setLayoutManager(new LinearLayoutManager(rv.getContext()));
    rv.setAdapter(listAdapter);//from ww w.  j a  va2 s .co m

    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            swipeLayout.setRefreshing(false);
        }
    };

    swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_layout);
    swipeLayout.setOnRefreshListener(this);

    return view;
}