编写我自己的Activity库,如何分离自定义部分?

时间:2016-01-21 10:33:41

标签: java android oop

我的应用中的许多活动都使用NFC前台调度,所以我写了这个类

通过扩展此类

,可以非常轻松地启用NFC前台调度功能
public class NfcActivity extends Activity {

    private PendingIntent pendingIntent;
    private NfcIntentReceiver nfcIntentReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("myaction"), 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (nfcIntentReceiver == null) {
            nfcIntentReceiver = new NfcIntentReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("myaction");
        registerReceiver(nfcIntentReceiver, intentFilter);

        IntentFilter[] filters = new IntentFilter[1];
        String[][] techList = new String[][]{};
        filters[0] = new IntentFilter();
        filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
        filters[0].addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
        filters[0].addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
        filters[0].addCategory(Intent.CATEGORY_DEFAULT);

        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, filters, techList);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (nfcIntentReceiver != null) {
            unregisterReceiver(nfcIntentReceiver);
        }
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        nfcAdapter.disableForegroundDispatch(this);
    }

    public class NfcIntentReceiver extends BroadcastReceiver {

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

            //custom code
        }
    }
}

但是这个类不应该在库中

应由用户实施

public class NfcIntentReceiver extends BroadcastReceiver {

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

        //custom code
    }
}

如何在库外分离这个类?

如果可能,请在库中保留registerReceiver和unregisterReceiver逻辑

0 个答案:

没有答案