与BroadcastReceiver的2个活动之间的通信

时间:2018-01-09 18:56:57

标签: android broadcastreceiver startactivityforresult

我必须在2个活动之间交换数据,第一个是管理数据,第二个是用标签管理通信NFC(总是在前台)。 第一个Activity使用startActivityForResult启动第二个Activity。 我实施了BroadCastReceiver来管理两个活动之间的双向交换。 startActivityForResult已经很好地启动了,我在DroidReader中获得了很好的数据,DroidReader返回给MainActivity的数据还可以。但是当我重新尝试MainActivity的context.sendBroadcast(i)以再次向DroidReader发送信息时,我从未对DroidReader方面有所了解。 TX为您提供了很多帮助。

这是MainActivity

   public class MainActivity extends Activity {

    private TextView mTextView;
    public static final String TAG = "MainDemo";
    final static int REQUEST_CODE = 1;


    private Receiver mReceiver;

    private class Receiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
             if (intent.getAction().equals("SOMEACTION")) {
                handleMessage(context, intent);
                 Log.i(TAG, "onReceive");
            }else
                 Log.i(TAG, "noT onReceive");
        }



        private void handleMessage(Context context, Intent intent) {
            byte[] retour = intent.getByteArrayExtra("Return");
           Log.i(TAG, "byte array : "+byteArrayToSHex(retour));
            Intent i = new Intent();
            i.setAction("android.intent.action.MAIN");
            i.putExtras(intent);
            Log.i(TAG, "passage dans handleMessage");
            // context.sendOrderedBroadcast(i, null);
            context.sendBroadcast(i);

          //  Intent i = new Intent("android.intent.action.AndroidReader").putExtra("APDUReturn", retour);
          //  this.sendBroadcast(i);
        }
    }

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

        mReceiver = new Receiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("SOMEACTION");
        this.registerReceiver(mReceiver, filter);

        mTextView = (TextView) findViewById(R.id.textView_explanation);

        Button start = (Button) findViewById(R.id.start_button);
        start.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, AndroidReader.class);
                byte[] data1 = {0x00, (byte) 0xA4};


                APDUBundle apduBundle = new APDUBundle(data1, true/*, intent*/);

                intent.putExtra("data", data1);//.putCharSequenceArrayListExtra(("paramFirst", seReq);
                intent.putExtra("case4", true);
                intent.setAction("android.intent.action.MAIN");
                Log.i(TAG, "MainActivity:Oncreate");

                startActivityForResult(intent,  REQUEST_CODE);

            }
        });





        public void onResume() {
            super.onResume();

            registerReceiver(myBroadcastReceiver, intentFilter);
        }

        public void onPause() {
            super.onPause();

            unregisterReceiver(myBroadcastReceiver);
        }

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE){
            if(resultCode == RESULT_OK){
                byte[] result=data.getByteArrayExtra("Return");
              //  APDUBundle apduBundle = getIntent().getParcelableExtra("APDUBundle");

                Toast.makeText(getApplicationContext(), /*byteArrayToSHex(apduBundle.getAPDU())*/byteArrayToSHex(result), Toast.LENGTH_SHORT).show();

            }
            if (resultCode == RESULT_CANCELED) {
                //Write your code if there's no result
                Toast.makeText(getApplicationContext(), "Nothing Returned!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        if(mReceiver!=null)
            this.unregisterReceiver(mReceiver);
    }
}

这是DroidReader

public class AndroidReader extends Activity  {

    public static final String MIME_TEXT_PLAIN = "text/plain";
    public static final String TAG = "NfcDemo";

    private TextView mTextViewNFC;
    private NfcAdapter mNfcAdapter;

    byte[] dataIntent = null;
    boolean case4Intent = false;

    Tag mTag = null ;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
//    private GoogleApiClient client;

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

        mTextViewNFC = (TextView) findViewById(R.id.textView_explanationNFC);

        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

        if (mNfcAdapter == null) {
            // Stop here, we definitely need NFC
            Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
            finish();
            return;

        }

        if (!mNfcAdapter.isEnabled()) {
            mTextViewNFC.setText("NFC is disabled.");
        } else {
            mTextViewNFC.setText(R.string.explanation);
        }




        handleIntent(getIntent());
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
      //  client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    protected void onResume() {
        super.onResume();

        /**
         * It's important, that the activity is in the foreground (resumed). Otherwise
         * an IllegalStateException is thrown.
         */
        setupForegroundDispatch(this, mNfcAdapter);
    }

    @Override
    protected void onPause() {
        /**
         * Call this before onPause, otherwise an IllegalArgumentException is thrown as well.
         */
        stopForegroundDispatch(this, mNfcAdapter);

        super.onPause();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        /**
         * This method gets called, when a new Intent gets associated with the current activity instance.
         * Instead of creating a new activity, onNewIntent will be called. For more information have a look
         * at the documentation.
         *
         * In our case this method gets called, when the user attaches a Tag to the device.
         */

        byte[] retour = handleIntent(intent);

        Log.i(TAG, "Return :"+byteArrayToSHex(retour));

        Intent i = new Intent("SOMEACTION").putExtra("Return", retour);
        this.sendBroadcast(i);
    }

    private byte[] handleIntent(Intent intent) {
        // TODO: handle Intent
        String action = intent.getAction();
        Log.i(TAG, "handleIntent :"+action);
        byte[] res = {};

         if ("android.intent.action.MAIN".equals(action)) {

               dataIntent = getIntent().getByteArrayExtra("data");
                  case4Intent = getIntent().getBooleanExtra("case4", true);

                Log.i(TAG, "value dataIntent:"+dataIntent);
                Log.i(TAG, "value case4Intent:"+case4Intent);
                 //   Log.i(TAG, "value getIntent:"+apduBundle.getIntent());
               res = {0x00};
        }
        return res;
    }

    /**
     * @param activity The corresponding {@link Activity} requesting the foreground dispatch.
     * @param adapter  The {@link NfcAdapter} used for the foreground dispatch.
     */
    public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
        final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);


        final PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);

        adapter.enableForegroundDispatch(activity, pendingIntent, null, null);
    }

    /**
     * @param activity The corresponding {@link BaseActivity} requesting to stop the foreground dispatch.
     * @param adapter  The {@link NfcAdapter} used for the foreground dispatch.
     */
    public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
        adapter.disableForegroundDispatch(activity);
    }

}

0 个答案:

没有答案