如何使用从另一个 activity 或主 class 调用 activity 中的处理程序

how to use call a handler in an activity from another activity or main class

我正在尝试使用输入输出流在 android 上与 USB 通信,因为我在 activity 中使用处理程序,它工作正常但如果在每个 activity 单独它不能正常工作所以我想做一个共同的 activity 并在 activity 中作为所有 activity 的调解人进行交流,我尝试了类似

public class BasicAccessoryDemo extends Activity implements View.OnClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button mycontrol, close_command;
        mycontrol = (Button) findViewById(R.id.send_command);
        mycontrol.setOnClickListener(this);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_command:
                byte[] commandPacket = new byte[2];
                commandPacket[0] =0x12;
                commandPacket[1] =0x34;
                Usb_Communciation.Send_message(commandPacket);
                break;
        }
    }

}

另一个持有处理程序的 class 是

public class Usb_Communciation extends Activity{
    public final static int USBAccessoryWhat = 0;
    public int firmwareProtocol = 0;
    public static USBAccessoryManager accessoryManager;
    public static String TAG = "MICROCHIP";
    public static final int APP_CONNECT                 = (int)0xAE;
    public boolean deviceAttached = false;

    public void onCreate(Bundle savedInstanceState) {
        accessoryManager = new USBAccessoryManager(handler, USBAccessoryWhat);
       //accessoryManager.enable(this, getIntent());
    }

    public static void Send_message(byte[] data) {
        try{
            accessoryManager.write(data);
        }catch (Exception e){
            Log.d(TAG,
                    "USBAccessoryManager:write():IOException: arasu "
                            + e.toString());
            e.printStackTrace();
        }
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            byte[] commandPacket = new byte[64];
            byte[] WriteValue = new byte[2];

            switch(msg.what)
            {
                case USBAccessoryWhat:
                    boolean StopReading = true;
                    int count = 0;
                    switch(((USBAccessoryManagerMessage)msg.obj).type)
                    {
                        case READ:
                            if(accessoryManager.isConnected() == false) {
                                return;
                            }
                            while(true) {
                                if (accessoryManager.available() < 2) {
                                    break;
                                }
                            }
                            break;
                        case READY:
                            String version = ((USBAccessoryManagerMessage)msg.obj).accessory.getVersion();
                            firmwareProtocol = getFirmwareProtocol(version);
                            switch(firmwareProtocol){
                                case 1:
                                    deviceAttached = true;
                                    break;
                                case 2:
                                    deviceAttached = true;
                                    commandPacket[0] = (byte) APP_CONNECT;
                                    commandPacket[1] = 0;
                                    accessoryManager.write(commandPacket);                                  
                                    Log.d(TAG,"connect message sent.");
                                    break;
                            }
                            break;
                    }
                    break;
            }   //switch
        } //handleMessage
    }; //handler

    public int getFirmwareProtocol(String version) {
        String major = "0";
        int positionOfDot;
        positionOfDot = version.indexOf('.');
        if(positionOfDot != -1) {
            major = version.substring(0, positionOfDot);
        }
        return new Integer(major).intValue();
    }
}

在这种情况下,我们使用 IntentService. Where you define an IntentService which is a class that will work in background when an action is received. Then you can process your input-output stream (in background!! which is what we want) and then send a broadcast to your activities using BroadcastReceiver

您使用的 activity class 与普通 java class 一样,我看到第二个 activity 没有任何视图文件.您可以使用构造函数创建一个名为 UsbCommunication 的普通 class,并在您的 activity 中对其进行初始化,如下所示:

public class Usb_Communciation {
    public final static int USBAccessoryWhat = 0;
    public int firmwareProtocol = 0;
    public static USBAccessoryManager accessoryManager;
    public static String TAG = "MICROCHIP";
    public static final int APP_CONNECT                 = (int)0xAE;
    public boolean deviceAttached = false;


    public Usb_Communciation (/*Pass neccesary parameters here from activity*/) {
       accessoryManager = new USBAccessoryManager(handler, USBAccessoryWhat);
    }


    public void Send_message(byte[] data) {
       try{
           accessoryManager.write(data);
       }catch (Exception e){
          Log.d(TAG,
                "USBAccessoryManager:write():IOException: arasu "
                        + e.toString());
        e.printStackTrace();
       }
   }

   public Handler handler = new Handler() {
       @Override
       public void handleMessage(Message msg) {
           byte[] commandPacket = new byte[64];
           byte[] WriteValue = new byte[2];

           switch(msg.what)
           {
            case USBAccessoryWhat:
                boolean StopReading = true;
                int count = 0;
                switch(((USBAccessoryManagerMessage)msg.obj).type)
                {
                    case READ:
                        if(accessoryManager.isConnected() == false) {
                            return;
                        }
                        while(true) {
                            if (accessoryManager.available() < 2) {
                                break;
                            }
                        }
                        break;
                    case READY:
                        String version = ((USBAccessoryManagerMessage)msg.obj).accessory.getVersion();
                        firmwareProtocol = getFirmwareProtocol(version);
                        switch(firmwareProtocol){
                            case 1:
                                deviceAttached = true;
                                break;
                            case 2:
                                deviceAttached = true;
                                commandPacket[0] = (byte) APP_CONNECT;
                                commandPacket[1] = 0;
                                accessoryManager.write(commandPacket);                                  
                                Log.d(TAG,"connect message sent.");
                                break;
                        }
                        break;
                }
                break;
        }   //switch
    } //handleMessage
}; //handler

   public int getFirmwareProtocol(String version) {
       String major = "0";
       int positionOfDot;
       positionOfDot = version.indexOf('.');
       if(positionOfDot != -1) {
        major = version.substring(0, positionOfDot);
    }
    return new Integer(major).intValue();
}

然后在您的 activity 中调用函数:

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.send_command:
            byte[] commandPacket = new byte[2];
            commandPacket[0] =0x12;
            commandPacket[1] =0x34;
            Usb_Communication usbCom = new Usb_Communication();
            usbCom.Send_message(commandPacket);
            break;
    }
}

您可以在您的应用程序中创建处理程序class。

public class YourApp extends Application {

    private Handler handler;

    @Override
    public void onCreate() {
        super.onCreate();
        handler = new Handler(Looper.getMainLooper());
    }

    public Handler getHandler() {
        return handler;
    }
}

然后您可以从其他组件获取处理程序,例如从Activity:

((YourApp)getApplication()).getHandler();

不要忘记在清单文件中设置应用程序名称。

<application
    android:name=".YourApp"
....>