简体   繁体   中英

Get intent from broadcast receiver to activity

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.

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

            }


        }
    }

}

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);
}
...
}

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();
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM