2

I want my activity class to receive an intent from broascast Receiver (example START_TALKING, STOP_TALKING). And when I receive that intent, I want to check what action was being passed. How can I do this. My receiver is in separate class, it's public.

Here's my code

public void onReceive(Context context, Intent intent)
{
    if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
        KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
                switch (event.getKeyCode()) {
    case KeyEvent.KEYCODE_HEADSETHOOK:
        if (action == KeyEvent.ACTION_DOWN)
            // here I want to notify my activity class (e.g.      startActivity? I don't know)
        break;
    case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
        // here I want to notify my activity class (e.g.      startActivity? I don't know)
              }
    }
}

I really need your help guys tnx.

blackpanther
  • 10,998
  • 11
  • 48
  • 78
Hisam Hershy
  • 91
  • 1
  • 3
  • 8
  • is you receiver registered and unregistered with applications start and stop ? – Rajen Raiyarela Apr 03 '15 at 05:30
  • 1
    If your receiver is just gonna be used by the activity, make the onReceive function abstract and register the receiver in the activity, and so you would be able to handle it in the activity. If your use case it different, as in you want to launch other activities, from the receiver, you could just use startActivity and pass the parameters through intent. Let me know if this helps – Ashish Kumar Apr 14 '18 at 07:10

3 Answers3

2

Here is my solution, in my project, hope it'll help you:

you should type this:
// put your action string in intent
Intent intent = new Intent("com.example.myproject.ADD_ITEM_BASKET");
// start broadcast
activity.sendBroadcast(intent);


public class Myclass extends Fragment {

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

    // creating and register receiver
    Receiver receiver = new Receiver();
    IntentFilter intentFilterAdd = new IntentFilter("com.example.myproject.ADD_ITEM_BASKET");
    IntentFilter intentFilterEdit = new IntentFilter("com.example.myproject.DELETE_ITEM_BASKET");


    getActivity().registerReceiver(receiver, intentFilterAdd);
    getActivity().registerReceiver(receiver, intentFilterDelete);

}
    // your receiver class 
    class Receiver extends BroadcastReceiver
    {

        // catch messages from intent
        @Override
        public void onReceive(Context context, Intent intent) {

            if("com.example.myproject.ADD_ITEM_BASKET".equals(intent.getAction().toString()))
            {

                // do something
            }
            else if("com.example.myproject.DELETE_ITEM_BASKET".equals(intent.getAction().toString()))
            {
                // do something

            }


        }
    }

}
Denis
  • 341
  • 1
  • 5
  • 19
  • I'm still confused. My problem is this,in my `onReceive` i did capture the headset button event. when `headset button is pressed` my condiotion is lyk this `if(KeyEvent.KEYCODE_MEDIA_PLAY:) { //hey MyActivity Class I want you to do this (..some method. .) }` – Hisam Hershy Sep 28 '13 at 19:46
  • what should I type after i receive the intent? lyk `if("com.myApp.app".equals(intent.getAction.tostring())){ Intent intent = (cotext, MyActivityClass.class) startActivity(intent) } ? – Hisam Hershy Sep 28 '13 at 19:49
  • Can I put an `action`? so that when i receive it on my activity I'm able to filter which action has been sent to my activty. – Hisam Hershy Sep 28 '13 at 19:51
  • i edited my answer. try this: `Intent intent = new Intent("com.example.myproject.ADD_ITEM_BASKET"); // start broadcast activity.sendBroadcast(intent);` – Denis Sep 28 '13 at 20:18
  • Where should I put this `Intent intent = new Intent("com.example.myproject.ADD_ITEM_BASKET"); // start broadcast activity.sendBroadcast(intent);`? in the onReceive? – Hisam Hershy Sep 28 '13 at 20:28
0

You can use putExtra() in your BroadcastReceiver's onReceive().

/**
 * @author Skylifee7 on 23/06/2017.
 * TemplateResultReceiver.java
 */

public class TemplateResultReceiver extends BroadcastReceiver {

        private static final String TAG = "BleshTemplate";
        public static final String EXTRA_MESSAGE = "TRANSACTION_MESSAGE";
        Context mContext;

        @Override
        public void onReceive(Context context, Intent intent) {

            mContext = context;

            if (intent.getAction().equals(BleshConstant.BLESH_TEMPLATE_RESULT_ACTION)) {

                String actionType = intent.getStringExtra(BleshConstant.BLESH_ACTION_TYPE);
                String actionValue = intent.getStringExtra(BleshConstant.BLESH_ACTION_VALUE);

                if (actionType != null && actionValue != null) {

                    switch (actionType) {
                        case "MENU": sendMessage(actionValue);
                        /*
                        You may want to increase the case possibilities here, like below:
                        case: "ADMOB"
                        case: "VIRTUAL_AVM"
                        case: "SMART_CAR_KEY"
                         */
                        default: sendMessage(actionValue);
                    }
                }
            }
    }

    private void sendMessage(String actionValue) {
        Intent intent = new Intent(mContext.getApplicationContext(),TransactionActivity.class);
        intent.putExtra(EXTRA_MESSAGE, actionValue);
        mContext.getApplicationContext().startActivity(intent);
    }
}

And in your Activity class' onCreate() method:

/**
 * @author Skylifee7 on 24/06/2017.
 * TransactionActivity.java
 */

public class TransactionActivity extends AppCompatActivity   {

    private String bleshKey;
    private String TAG = "Transaction_Activity";
    private String amount;
    private String isSuccessful; //may be cast to boolean type.
    private double latitude, longitude;

    private LocationRequest mLocationRequest;
    protected GoogleApiClient mGoogleApiClient;

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

        requestPermission();
        initLocationService();
        // Get the Intent that started this activity and extract the string
        Intent intent = getIntent();
        bleshKey = intent.getStringExtra(BleshTemplateResultReceiver.EXTRA_MESSAGE);

        ImageButton paymentBtn = (ImageButton) findViewById(R.id.buttonPay);
        final EditText editTextAmount = (EditText) findViewById(R.id.editTextAmount);

        paymentBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                amount = editTextAmount.getText().toString();
                callApiService();
            }
        });
    }
}
gokcand
  • 6,694
  • 2
  • 22
  • 38
-1

You have to register the receiver... Follow this example..

public class MyActivity extends Activity {

private BroadcastReceiver myBroadcastReceiver =
    new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // your onreceive code here
        }
   });

...

public void onResume() {
    super.onResume();
    ....
    registerReceiver(myBroadcastReceiver, intentFilter);
}

public void onPause() {
    super.onPause();
    ...
    unregisterReceiver(myBroadcastReceiver);
}
...
}
Micer
  • 8,731
  • 3
  • 79
  • 73
amalBit
  • 12,041
  • 6
  • 77
  • 94
  • But how do I send the action from my broadcast receiver to my activity. I only have 1 broadcast receiver. – Hisam Hershy Sep 28 '13 at 19:09
  • I mean, I only have 1 broadcast receiver and I need to send data to do some method in several activity depends on the situation. – Hisam Hershy Sep 28 '13 at 19:12