android2018. 9. 4. 14:02

/* ****************************************************************************

 * HOW TO DECIDE WHERE YOUR KEY HANDLING GOES.

 *

 * If your key handling must happen before the app gets a crack at the event,

 * it goes in PhoneWindowManager.

 *

 * If your key handling should happen in all windows, and does not depend on

 * the state of the current application, other than that the current

 * application can override the behavior by handling the event itself, it

 * should go in PhoneFallbackEventHandler.

 *

 * Only if your handling depends on the window, and the fact that it has

 * a DecorView, should it go here.

 * ****************************************************************************/


Android KeyEvent의 처리 순서


기본적으로 KeyEvent의 처리는 application 내부에서 재정의한다.

만약 처리하지 않으면 이벤트는 최종적으로 PhoneFallbackEventHandler로 떨어지게 된다.


1, PhoneWindowManager.java -> interceptKeyBeforeDispatching 

: 가장 먼저 처리되어야 하는 KeyEvent들의 처리

2, PhoneWindow.java -> onKeyUp and onKeyDown

: KeyEvent의 처리가 window에 종속적인 경우 PhoneWindow에서 처리.

3, PhoneFallbackEventHandler.java -> dispatchKeyEvent

: 모든 KeyEvent의 처리가 Window에 의존하지 않고 처리되어야하는 경우, PhoneFallbackEventHandler에 정의한다.




각 1,2,3의 처리 부분에서 true를 리턴하는 경우 다음 stage의 handler에는 전달되지 않고 consume 된다.



출처 :

AOSP source code

Posted by easy16
android2018. 8. 31. 16:22


Early suspend -> suspend =======> resume -> late resume


링크 : 

http://egloos.zum.com/taehyo/v/4091452

Posted by easy16
android2018. 8. 30. 10:01
import java.lang.reflect.Method;

public class Test {

public static void readProperty(){
final String parmName = "paramName";
final String defaultParamName="foo";
try {

@SuppressWarnings("rawtypes")
Class SystemProperties = Class.forName("android.os.SystemProperties");
Method set1 = SystemProperties.getMethod("get", new Class[] {String.class, String.class});
String properties = (String) set1.invoke(SystemProperties, new Object[] {parmName, defaultParamName});

} catch( IllegalArgumentException iAE ){
throw iAE;
} catch( Exception e ){
e.printStackTrace();
}


}
}


Posted by easy16
android2018. 8. 22. 15:35

sendBroadcast할 경우,  아래와 같이 Error 메시지가 뜰 경우가 있다.

E ActivityManager: Sending non-protected broadcast 


그럴 때 AndroidManifest.xml 에 targetSdkVersion이 빠져있는지 확인해보도록 하자

-       <uses-sdk android:minSdkVersion="19"/>

+    <uses-sdk

+        android:targetSdkVersion="25"

+        android:minSdkVersion="25"/>




출처 : 

https://stackoverflow.com/questions/43354717/i-always-see-e-activitymanager-sending-non-protected-broadcast-from-system-in

Posted by easy16
android2018. 8. 10. 16:13


하기 링크 참조:

http://snowdeer.github.io/android/2017/08/08/android-studio-aidl-example/

'android' 카테고리의 다른 글

property read using reflection java  (0) 2018.08.30
ErrorMessage: Sending non-protected broadcast  (0) 2018.08.22
android:process  (0) 2018.08.10
Immediate Audio Input & Output Android  (0) 2018.07.26
AudioTrack 정리  (0) 2018.07.26
Posted by easy16
android2018. 8. 10. 15:16



설명 :

프로세스

기본적으로 같은 애플리케이션의 모든 구성 요소는 같은 프로세스와 스레드에서 실행되고, 대부분의 애플리케이션은 이를 바꿔서는 안됩니다. 그러나 어느 프로세스가 특정 구성 요소에 속하는지 확인해야 할 경우 매니페스트 파일에서 확인할 수 있습니다.

각 유형의 구성 요소(<activity><service><receiver> 및 <provider>)에 대한 매니페스트 항목은 이 구성 요소가 실행되는 프로세스를 지정할 수 있는 android:process 특성을 지원합니다. 이러한 특성을 설정하여 각 구성 요소를 자체 프로세스에서 실행시키거나 다른 구성 요소를 제외한 일부 구성 요소만 프로세스를 공유하게 할 수 있습니다 또한,android:process를 설정하여 다른 애플리케이션의 구성 요소를 동일한 프로세스에서 실행시킬 수도 있습니다. 단, 이는 애플리케이션이 동일한 Linux 사용자 ID를 공유하고 동일한 인증서로 서명되었을 경우에 한합니다.

<application> 요소도 android:process 특성을 지원하여, 모든 구성 요소에 적용되는 기본값을 설정합니다.

Android는 어느 시점엔가 프로세스를 종료하기로 결정할 수도 있습니다. 즉 메모리가 부족하거나, 사용자에게 더욱 즉각적인 서비스를 제공하는 다른 프로세스가 이 프로세스의 중단을 필요로 하는 경우 등입니다. 그러면 중단된 프로세스에서 실행되고 있던 애플리케이션 구성 요소도 따라서 소멸됩니다. 그와 같은 구성 요소가 할 작업이 다시 생기면 그에 대한 프로세스도 다시 시작됩니다.

어느 프로세스를 삭제할지 결정할 때, Android 시스템은 사용자에 대한 이들의 상대적 중요성을 가늠합니다. 예를 들어, 눈에 보이는 액티비티를 호스팅하는 프로세스와 비교하여 화면에 보이지 않는 액티비티를 호스팅하는 프로세스를 쉽게 종료할 수 있습니다. 프로세스 종료 결정은 해당 프로세스에서 실행되는 구성 요소의 상태에 따라 달라집니다. 종료할 프로세스를 결정하는 데 사용하는 규칙은 아래에 설명되어 있습니다.



출처 :

https://developer.android.com/guide/components/processes-and-threads?hl=ko

'android' 카테고리의 다른 글

ErrorMessage: Sending non-protected broadcast  (0) 2018.08.22
AIDL example API + Callback (link)  (0) 2018.08.10
Immediate Audio Input & Output Android  (0) 2018.07.26
AudioTrack 정리  (0) 2018.07.26
MediaPlayer  (0) 2018.07.18
Posted by easy16
android2018. 7. 26. 18:29

Immediate Audio Input & Output Android

#1. Recording한 파일을 즉시 읽어 재생하는 방법


final Thread record = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!Thread.interrupted()) {
                MediaRecorder microphone = new MediaRecorder();
                microphone.setAudioSource(MediaRecorder.AudioSource.MIC);
                    microphone.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                microphone.setOutputFile(filename);
                microphone.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                try {
                    microphone.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                microphone.start();
            }
        }
    });

    final Thread play = new Thread(new Runnable() {
        @Override
        public void run() {
            while (!Thread.interrupted()) {
                player = new MediaPlayer();
                try {
                    player.setDataSource(filename);
                    player.prepare();
                    player.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });


#2. AudioRecord 객체로 부터 즉시 재생하는 방법


      recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
      RECORDER_SAMPLERATE, RECORDER_CHANNELS,
      RECORDER_AUDIO_ENCODING, bufferSize * BytesPerElement);

    recorder.startRecording();

    isRecording = true;

    recordingThread = new Thread(new Runnable() {

     public void run() {

      try {
          int intSize = android.media.AudioTrack.getMinBufferSize(RECORDER_SAMPLERATE,AudioFormat.CHANNEL_OUT_MONO , RECORDER_AUDIO_ENCODING);
          byte[] sData = new byte[bufferSize];
          AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLERATE, AudioFormat.CHANNEL_OUT_MONO, RECORDER_AUDIO_ENCODING, intSize, AudioTrack.MODE_STREAM);
          while(isRecording){
          recorder.read(sData, 0, bufferSize);  //isRecording = false; onStop button

          if (at!=null) { 
              at.play();
              // Write the byte array to the track
              at.write(sData, 0, sData.length); 
              at.stop();
              at.release();
          }
          }
    } catch (IOException e) {
        e.printStackTrace();
    }
 }
  }, "AudioRecorder Thread");
    recordingThread.start();


출처 :

https://stackoverflow.com/questions/34489339/immediate-audio-input-output-android

'android' 카테고리의 다른 글

AIDL example API + Callback (link)  (0) 2018.08.10
android:process  (0) 2018.08.10
AudioTrack 정리  (0) 2018.07.26
MediaPlayer  (0) 2018.07.18
Single Fragment 예제  (0) 2018.07.16
Posted by easy16
android2018. 7. 26. 18:24

AudioTrack


Developer site에 올라온 기본적인 내용은 아래와 같다.


- java 단의 single audio resource를 재생 및 관리

- 재생을 위해 PCM streaming audio buffer를 audio sink에 허가

- "pushing"이라는 액션을 통해 가능하며 AudioTrack 객체에 data를 write 메서드를 이용한다.

  AudioTrack에 data write 행위를 pushing이라하며 이것이 결국 audio sink에 pcm stream을 audio buffer를 통해 가능하다는 소리.


- AudioTrack의 두가지 모드 (static/streaming)

- streaming mode 모드에서는 application이 AudioTrack에 stream을 끊임없이 write함. 당연 write 메소드 이용.

- blocking함수이며, java에서 native로 데이터 전송이 끝나고 재생을 위한 큐잉이 끝나면 리턴한다.

- streaming mode가 유용한 경우는 아래와 같다.

- play를 위한 duration이 길어 데이터 사이즈가 너무 크고 메모리에 fit하지 않는 경우.

- audio data특성으로 인해 (high sampling rate, bits per sample ...) 메모리가 부족한 경우.

- 이전 큐된 데이터가 재생 중에 또다른 데이터가 생성 또는 전달 된 경우.

 

 -static mode는 데이터 사이즈가 작아 메모리 fit이 맞는 경우 그리고 가장적은 latency가 가능하도록 재생해야 하는 경우 사용된다.

 

 - AudioTrack 객체가 생성될 떄, 전송을 위한 audio buffer가 초기화 된다. 

 - 이때 사용된 버퍼 사이즈는 AudioTrack이 데이터가 다 쓰이기전에 재생할 수 있는 기간을 결정하게 된다.

 - static mode를 쓰는 AudioTrack은 이 떄 정한 사이즈가 AudioTrack에서 재생할 수 있는 최대 사이즈 이다.

 - Streaming mode에서는 audio sink로 최대 버퍼 사이즈보다 작거나 같은 수준으로 chunk data를 쓴다.



AudioTrack 객체 생성은 AudioTrack.Builder를 통해서 진행한다.

예시는 아래와 같으며 크게 다른 내용이 없는 경우엔 그대로 적용가능.

 AudioTrack player = new AudioTrack.Builder()
         
.setAudioAttributes(new AudioAttributes.Builder()
                 
.setUsage(AudioAttributes.USAGE_ALARM)
                 
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                 
.build())
         
.setAudioFormat(new AudioFormat.Builder()
                 
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
                 
.setSampleRate(44100)
                 
.setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
                 
.build())
         
.setBufferSizeInBytes(minBuffSize)
         
.build();


출처 : 


AudioTrack

https://developer.android.com/reference/android/media/AudioTrack


AudioTrack.Builder

https://developer.android.com/reference/android/media/AudioTrack.Builder#setPerformanceMode(int)

'android' 카테고리의 다른 글

android:process  (0) 2018.08.10
Immediate Audio Input & Output Android  (0) 2018.07.26
MediaPlayer  (0) 2018.07.18
Single Fragment 예제  (0) 2018.07.16
Custom Intent로 app 실행하기  (0) 2018.07.16
Posted by easy16
android2018. 7. 18. 10:15

MediaPlayer 

(android.media.MediaPlayer)


MediaPlayer를 조작시, 아래 상태도에 대해 충분히 숙지해야함.

설명은 하기 developer 사이트 참조




출처 : 

https://developer.android.com/reference/android/media/MediaPlayer

'android' 카테고리의 다른 글

Immediate Audio Input & Output Android  (0) 2018.07.26
AudioTrack 정리  (0) 2018.07.26
Single Fragment 예제  (0) 2018.07.16
Custom Intent로 app 실행하기  (0) 2018.07.16
tutorialspoint  (0) 2018.07.16
Posted by easy16
android2018. 7. 16. 16:02

About Fragment


-Fragment는 자신만의 layout 및 lifecycle을 가진다.

-Running 중인 Activity 내에서 add/remove가능하다.

-하나의 Activity 여러개의 Fragment는 사용할 수 있다.

-하나의 Fragment는 여러 Activity에서 활용할 수 있다.

-Activity life-cycle과 매우 유사, Activity 멈추면 Fragment는 같이 멈춘다.

-UI없는 Fragment 구현가능하다.


Example) Single Fragment



public class LM_Fragment extends Fragment {
    static final String TAG=LM_Fragment.class.getSimpleName();
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        return inflater.inflate(R.layout.lm_fragment, container, false);
    }
}
public class FragmentActivity extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Configuration config = getResources().getConfiguration();


        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (config.orientation == Configuration.ORIENTATION_LANDSCAPE){
            Fragment lm=  new LM_Fragment();
            fragmentTransaction.replace(android.R.id.content, lm);
        } else {
            Fragment pm=  new PM_Fragment();
            fragmentTransaction.replace(android.R.id.content, pm);

        }
        fragmentTransaction.commit();
    }

}



lm_fragment.xml


<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout

    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"

    android:layout_height="match_parent">


    <LinearLayout

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:orientation="horizontal"

        android:background="@color/fui_linkColor"

        >


        <TextView

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:text="LM_Fragment"

            android:textColor="#000000"

            android:textSize="20px" />

    </LinearLayout>


</android.support.constraint.ConstraintLayout>


AndroidManifest.xml

<activity android:name=".FragmentActivity">


</activity>


출처 : https://www.tutorialspoint.com/index.htm

'android' 카테고리의 다른 글

AudioTrack 정리  (0) 2018.07.26
MediaPlayer  (0) 2018.07.18
Custom Intent로 app 실행하기  (0) 2018.07.16
tutorialspoint  (0) 2018.07.16
custom view tutorial 따라하기 3  (0) 2018.07.16
Posted by easy16