마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

메인 액티비티의 메소드를 다른 액티비티에서 쓰고 싶습니다.

0 추천
public class MainActivity extends AppCompatActivity {

    TextView ex;
    int ledflag = 0;
    //사용자 정의 함수로 블루투스 활성화 상태의 변경 결과를 앱으로 알려줄때 식별자로 사용
    static final int REQUEST_ENABLE_BT = 10;
    int mPariedDeviceCount = 0;
    Set<BluetoothDevice> mDevices;
    //스마트폰의 블루투스 모듈을 사용하기 위한 오브젝트
    BluetoothAdapter mBluetoothAdapter;
    /*
    기기의 장치정보를 알아낼 수 있는 자세한 메소드 및 상태값을 알아낼 수 있음
    연결하고자 하는 다른 블루투스 기기의 정보를 조회할 수 있는 클래스
    현재 기기가 아닌 다른 블루투스 기기와의 연결 및 정보를 알아낼 때 사용
    */
    BluetoothDevice mRemoteDevices;
    //스마트폰과 페어링 된 디바이스간 통신채널에 대응
    BluetoothSocket mSocket = null;
    OutputStream mOutputStream = null;
    InputStream mInputStream = null;
    String mStrDelimiter = "\n";
    char mCharDelimiter = '\n';
    Thread mWorkerThread = null;
    byte[] readBuffer;
    int readBufferPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        ex = (TextView) findViewById(R.id.ex);
    }

    public void onClickBLU(View v) {
        checkBluetooth(); //앱 시작과 동시에 블루투스 체크
    }

    public void onClickWIFI(View v) {
            if(ledflag ==0){
                ex.setText("a");
                sendData(ex.getText().toString());
                ledflag = 1;
            }
            else{
                ex.setText("b");
                sendData(ex.getText().toString());
                ledflag = 0;
            }

        }


    public void onClick02(View v) {
        Intent intent_02 = new Intent(getApplicationContext(), auto.class);
        startActivity(intent_02);
    }

    public void onClick03(View v) {
        Intent intent_03 = new Intent(getApplicationContext(), manual.class);
        startActivity(intent_03);
    }

    //기기로 데이터 전송
    void sendData(String msg) {
        msg += mStrDelimiter;
        try { //Byte단위로 데이터 전송
            mOutputStream.write(msg.getBytes());
        } catch (Exception e) { //데이터 전송중 오류가 발생 한 경우
            Toast.makeText(getApplicationContext(), "데이터 전송중 오류가 발생", Toast.LENGTH_LONG).show();
            finish(); //앱 종료
        }
    }

    //데이터 수신 (쓰레드 사용)
    void beginListenForData() {
        final Handler handler = new Handler();
        readBufferPosition = 0;
        readBuffer = new byte[1024];
        mWorkerThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        int byteAvailable = mInputStream.available();
                        if (byteAvailable > 0) {
                            byte[] packetBytes = new byte[byteAvailable];
                            mInputStream.read(packetBytes);
                            for (int i = 0; i < byteAvailable; i++) {
                                byte b = packetBytes[i];
                                if (b == mCharDelimiter) {
                                    byte[] encodedBytes = new byte[readBufferPosition];
                                    System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                    final String data = new String(encodedBytes, "US-ASCII");
                                    readBufferPosition = 0;
                                    handler.post(new Runnable() { //수신 된 데이터 처리
                                        @Override
                                        public void run() { //데이터를 받아올 경우 사용
                                        }
                                    });
                                } else {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    } catch (Exception e) { //데이터 수신 중 오류 발생
                        Toast.makeText(getApplicationContext(), "데이터 수신 중 오류가 발생 했습니다.",
                                Toast.LENGTH_LONG).show();
                        finish(); //앱 종료
                    }
                }
            }
        });
        mWorkerThread.start();
    }

    

블루투스로 아두이노에 버튼을 눌렀을 때 문자를 날리는 앱을 만들고 있습니다

대부분이 메인 액티비티에 있어서 나머지 액티비티에서도 문자전송을 하려는데

 

 

public class auto extends MainActivity {
    TextView ex;

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

    }

    public void onClick_sound(View v){
        Intent intent_sound = new Intent(getApplicationContext(), sound.class);
        startActivity(intent_sound);
    }

    public void autoStart(View v) {
            ex.setText("a");
            sendData(ex.getText().toString());
            }

}

 

이 액티비티에서 버튼을 누르면 전송중 오류가 발생만 뜹니다.

액티비티 상속이 문제인가 잘 모르겠어서 해매는중입니다.

블루투스 관련 코드는 길이상 생략했으며 메인 액티비티에서의 문자 전송은 잘 됩니다

메인 액티비티의 메소드 다른 액티비티에서 사용에 문제발생 님이 2018년 8월 14일 질문

1개의 답변

0 추천

http://arabiannight.tistory.com/entry/330

이런식으로 사용할수 있습니다. 다만 메인액티비티가 액티비티스택에 있어야만 가능하구, 메인액티비티가 생성되어있지 않은 상태에서는 context를 가져올수 없기 때문에 사용할 수 없습니다. 도움이 되길 바랍니다! 화이팅

 

idontknow (6,380 포인트) 님이 2018년 8월 15일 답변
감사합니다 드디어 해결됐어요 정말 감사합니다 ㅠㅠ
...