새소식

Daily Record

6월 2주차 학습 내용 정리

 

 

 

Android

 

1. Activity와 Intent

 - Activity : 안드로이드폰에 나타나는 화면 하나하나를 말하며 여러개의 Activity를 사용하여 화면을 구성할 수 있음

 - 일반적으로 액티비티 하나 당 xml 파일 하나를 만들어 사용

 - Intent : Activity, Service와 같은 안드로이드의 4대 컴포넌트가 서로 데이터를 주고받기 위한 메시지 객체.

   명시적 인텐트와 암시적 인텐트로 구분됨

 - 명시적 인텐트(explicit intent) : 다른 액티비티의 이름을 명확히 지정할 때 사용

 - 암시적 인텐트(implicit intent) : 약속된 액션을 지정하여 안드로이드에서 제공하는 기존 응용 프로그램 실행

 - 양방향 액티비티 : 두개의 액티비티가 서로 데이터를 주고 받음

 - 양방향 액티비티 연습(Main에서 계산할 값을 입력 -> Second에서 값 계산 -> Main에서 결과값 출력)

   * activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:padding="20dp">

    <EditText
        android:id="@+id/edit1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/edit2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"/>
    <RadioGroup
        android:id="@+id/rdGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <RadioButton
            android:id="@+id/rdAdd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="더하기"
            android:checked="true"/>
        <RadioButton
            android:id="@+id/rdSub"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="빼기"/>
        <RadioButton
            android:id="@+id/rdMul"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="곱하기"/>
        <RadioButton
            android:id="@+id/rdDiv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="나누기"/>
    </RadioGroup>
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="계산하기"
        android:layout_marginTop="20dp"/>

</LinearLayout>

   * activity_second.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity"
    android:orientation="vertical"
    android:padding="20dp">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="돌아가기"/>
</LinearLayout>

   * MainActivity.java

public class MainActivity extends AppCompatActivity {

    EditText edit1, edit2;
    RadioGroup rdGroup;
    Button button;
    final public int ADD = 0;
    final public int SUB = 1;
    final public int MUL = 2;
    final public int DIV = 3;
    int status = ADD;

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

        edit1 = findViewById(R.id.edit1);
        edit2 = findViewById(R.id.edit2);
        rdGroup = findViewById(R.id.rdGroup);
        button = findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float num1 = Float.valueOf(edit1.getText().toString());
                float num2 = Float.valueOf(edit2.getText().toString());
                Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
                intent.putExtra("num1", num1);
                intent.putExtra("num2", num2);
                intent.putExtra("status", status);
                startActivityForResult(intent, 0);
            }
        });

        rdGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                int id = rdGroup.getCheckedRadioButtonId();
                switch (id) {
                    case R.id.rdAdd:
                        status = ADD;
                        break;
                    case R.id.rdSub:
                        status = SUB;
                        break;
                    case R.id.rdMul:
                        status = MUL;
                        break;
                    case R.id.rdDiv:
                        status = DIV;
                        break;
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK) {
            float result = intent.getFloatExtra("result", 0);
            Toast.makeText(this, "결과 : " + result, Toast.LENGTH_LONG).show();
        }
    }
}

   * SecondActivity.java

public class SecondActivity extends AppCompatActivity {

    Button button;
    int status;
    float result, num1, num2;

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

        button = findViewById(R.id.button);

        Intent intent = getIntent();
        num1 = intent.getFloatExtra("num1", 0);
        num2 = intent.getFloatExtra("num2", 0);
        status = intent.getIntExtra("status", 0);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                switch (status) {
                    case 0 :
                        result = num1 + num2;
                        break;
                    case 1:
                        result = num1 - num2;
                        break;
                    case 2:
                        result = num1 * num2;
                        break;
                    case 3:
                        result = num1 / num2;
                        break;
                }
                intent.putExtra("result", result);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }
}

 

 

2. AdapterView - ListView / GridView

 - 어댑터뷰 : 그리드뷰, 리스트뷰, 스피너 등을 묶어서 어댑터뷰라고 함

 - 어댑터뷰를 사용할 때는 어댑터뷰의 모양을 설정하고 데이터를 채워주는 ArrayAdapter<T> 클래스,

    또는 사용자가 정의한 Adapter 클래스를 사용함

 - ListView : 데이터를 리스트 모양으로 보여주고 그 중 하나를 선택하는 용도로 사용

    ex) 폰 설정창

 - GridView : 사진이나 그림을 격자 모양으로 배치

 - Adapter 클래스를 정의하여 ListView 설정하기 연습(나라별 국기, 이름, 수도가 있는 리스트뷰)

   * activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
        
</LinearLayout>

   * view_cell.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="20dp"
    android:id="@+id/viewLayout">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/flag1"
        android:layout_marginRight="30dp"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="center_vertical">
        <TextView
            android:id="@+id/textNation"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="대한민국"
            android:textSize="25sp"
            android:layout_marginBottom="5dp"/>
        <TextView
            android:id="@+id/textCapital"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="서울"
            android:textSize="15sp"
            android:layout_marginLeft="1dp"/>
    </LinearLayout>

</LinearLayout>

   * MainActivity.java

public class MainActivity extends AppCompatActivity {

    ListView listView;
    List<NationDto> list = new ArrayList<>();
    String[] nations = {"대한민국", "몰디브", "싱가포르", "태국",
                        "가나", "이집트", "그리스", "네덜란드",
                        "모나코", "스위스", "미국", "캐나다", "호주"};
    String[] capitals = {"서울", "말레", "싱가포르", "방콕",
                        "아크라", "카이로", "아테네", "암스테르담",
                        "모나코", "베른", "워싱턴", "오타와", "캔버라"};
    MyAdapter adapter;

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

        listView = findViewById(R.id.listView);

        for (int i = 0; i < nations.length; i++) {
            int drawable = getResources().getIdentifier("flag" + (i+1),
                                                "drawable", getPackageName());
            String nation = nations[i];
            String capital = capitals[i];
            NationDto dto = new NationDto(drawable, nation, capital);
            list.add(dto);
        }
        adapter = new MyAdapter(getApplicationContext(), R.layout.view_cell, list);
        listView.setAdapter(adapter);
    }
}

   * MyAdapter.java

public class MyAdapter extends BaseAdapter {

    Context context;
    int resource;
    List<NationDto> list;

    public MyAdapter(Context context, int resource, List<NationDto> list) {
        this.context = context;
        this.resource = resource;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (view == null) {
            view = View.inflate(context, resource, null);
        }
        ImageView imageView = view.findViewById(R.id.imageView);
        TextView textNation = view.findViewById(R.id.textNation);
        TextView textCapital = view.findViewById(R.id.textCapital);
        LinearLayout viewLayout = view.findViewById(R.id.viewLayout);

        NationDto dto = list.get(i);
        int drawable = dto.getDrawable();
        String nation = dto.getNation();
        String capital = dto.getCapital();

        imageView.setImageResource(drawable);
        textNation.setText(nation);
        textCapital.setText(capital);

        if ((i%2) == 0) viewLayout.setBackgroundColor(Color.rgb(234, 250, 241));
        else viewLayout.setBackgroundColor(Color.rgb(235, 245, 251 ));
        // 인덱스에 따른 레이아웃 컬러 설정은 Main이 아니라 여기서 설정해야 함

        return view;
    }
}

   * NationDto.java

public class NationDto {
    int drawable;
    String nation, capital;

    public NationDto(int drawable, String nation, String capital) {
        this.drawable = drawable;
        this.nation = nation;
        this.capital = capital;
    }

    public int getDrawable() {
        return drawable;
    }

    public void setDrawable(int drawable) {
        this.drawable = drawable;
    }

    public String getNation() {
        return nation;
    }

    public void setNation(String nation) {
        this.nation = nation;
    }

    public String getCapital() {
        return capital;
    }

    public void setCapital(String capital) {
        this.capital = capital;
    }

    @Override
    public String toString() {
        return "NationDto{" + "drawable=" + drawable + ", nation='" + nation + '\'' +
               				 ", capital='" + capital + '\'' + '}';
    }
}

 

 

3. SQLite

 - 컴퓨터에서 구동되는 데이터베이스와 동일한 역할을 하며 모바일 환경에 최적화한 데이터베이스

 - 사용자가 선택한 날짜에 작성한 텍스트를 데이터베이스에 저장, 수정, 삭제, 조회 기능 구현

   * activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:padding="20dp">

    <DatePicker
        android:id="@+id/datePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:datePickerMode="spinner"
        android:calendarViewShown="false"
        android:layout_gravity="center"/>

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#FBEBFD"
        android:layout_marginBottom="10dp"
        android:gravity="top"
        android:padding="20dp"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnInsert"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="입력하기"
            android:backgroundTint="#BD54CF"
            android:layout_weight="1"
            android:layout_marginRight="5dp"/>
        <Button
            android:id="@+id/btnDelete"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="삭제하기"
            android:backgroundTint="#BD54CF"
            android:layout_weight="1"
            android:layout_marginLeft="5dp"/>
    </LinearLayout>

</LinearLayout>

   * MyDiaryVo.java

public class MyDiaryVo {
    String text, date;

    public MyDiaryVo(String date, String text) {
        this.text = text;
        this.date = date;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "MyDiaryDto{" + "text='" + text + '\'' + ", date='" + date + '\'' + '}';
    }
}

   * MyDiaryDao.java

public class MyDiaryDao {
    MyHelper helper;

    public MyDiaryDao(MyHelper helper) {
        this.helper = helper;
    }

    private void closeAll(SQLiteStatement statement, SQLiteDatabase sqLiteDatabase, Cursor cursor) {
        if (statement != null) statement.close();
        if (sqLiteDatabase != null) sqLiteDatabase.close();
        if (cursor != null) cursor.close();
    }

    // 입력
    public boolean insert(MyDiaryVo vo) {
        SQLiteDatabase sqLiteDatabase = helper.getWritableDatabase();
        String sql = "insert into tbl_diary" +
                "       values(?, ?)";
        SQLiteStatement statement = sqLiteDatabase.compileStatement(sql);
        statement.bindString(1, vo.getDate());
        statement.bindString(2, vo.getText());
        statement.executeInsert();
        closeAll(statement, sqLiteDatabase, null);

        return true;
    }

    // 수정
    public boolean update(MyDiaryVo vo) {
        SQLiteDatabase sqLiteDatabase = helper.getWritableDatabase();
        String sql = "update tbl_diary set text = ? where date = ?";
        SQLiteStatement statement = sqLiteDatabase.compileStatement(sql);
        statement.bindString(1, vo.getText());
        statement.bindString(2, vo.getDate());
        statement.executeUpdateDelete();
        closeAll(statement, sqLiteDatabase, null);
        return true;
    }

    // 삭제
    public boolean delete(String date) {
        SQLiteDatabase sqLiteDatabase = helper.getWritableDatabase();
        String sql = "delete from tbl_diary where date = ?";
        SQLiteStatement statement = sqLiteDatabase.compileStatement(sql);
        statement.bindString(1, date);
        statement.executeUpdateDelete();
        closeAll(statement, sqLiteDatabase, null);
        return true;
    }

    // 조회
    public String select(String date) {
        SQLiteDatabase sqLiteDatabase = helper.getReadableDatabase();
        String sql = "select * from tbl_diary where date = '" + date +"'";
        Cursor cursor = sqLiteDatabase.rawQuery(sql, null);
        String text = "";
        while (cursor.moveToNext()) { // while문이 없으면 오류가 발생하는데 가져올 값이 한개여도 꼭 써야하는지?
            text = cursor.getString(1);
        }
        closeAll(null, sqLiteDatabase, cursor);
        return text;
    }

}

   * MyHelper.java

public class MyHelper extends SQLiteOpenHelper {

    public MyHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String sql = "create table tbl_diary(" +
                "       date char(10) primary key," +
                "       text varchar(300))";
        sqLiteDatabase.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {}
}

   * MainActivity.java

public class MainActivity extends AppCompatActivity {

    DatePicker datepicker;
    EditText editText;
    Button btnInsert, btnDelete;
    int year, month, day;
    MyDiaryDao dao;
    MyHelper helper;
    String prevText;
    boolean isThere;

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

        datepicker = findViewById(R.id.datePicker);
        editText = findViewById(R.id.editText);
        btnInsert = findViewById(R.id.btnInsert);
        btnDelete = findViewById(R.id.btnDelete);

        helper = new MyHelper(this, "diary.db", null, 1);
        dao = new MyDiaryDao(helper);

        initCalandar();

        btnInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String date = year + "_" + month + "_" + day;
                String text = editText.getText().toString();
                String str = "";
                boolean result = false;
                if (!isThere) {
                    result = dao.insert(new MyDiaryVo(date, text));
                    str = "입력";
                } else {
                    Log.d("mytag", "edit");
                    result = dao.update(new MyDiaryVo(date, text));
                    str = "수정";
                }
                if (result)
                    Toast.makeText(MainActivity.this,
                            str + " 완료", Toast.LENGTH_SHORT).show();
            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String date = year + "_" + month + "_" + day;
                boolean result = dao.delete(date);
                if (result) Toast.makeText(MainActivity.this,
                            "삭제 완료", Toast.LENGTH_SHORT).show();
                editText.setText("");
                btnInsert.setText("입력하기");
            }
        });

        datepicker.setOnDateChangedListener(new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker datePicker, int year, int month, int day) {
                MainActivity.this.year = year;
                MainActivity.this.month = month + 1;
                MainActivity.this.day = day;
                String date = year + "_" + (month+1) + "_" + day;
                setPrevText(date);
            }
        });
    }

    private void initCalandar() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        String date = year + "_" + month + "_" + day;
        setPrevText(date);
    }

    private void setPrevText(String date) {
        prevText = dao.select(date);
        editText.setText(prevText);
        if (prevText == null || prevText.equals("")) {
            btnInsert.setText("입력하기");
            isThere = false;
        } else {
            btnInsert.setText("수정하기");
            isThere = true;
        }
    }
}

 

4. MediaPlayer

 - 멀티미디어를 동작시키기 위해 제공되는 클래스로 음악, 동영상을 재생하게 해줌

 - mp3 플레이어 앱 만들기 연습

   * activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:padding="20dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6">
        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </ListView>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center_vertical">
        <Button
            android:id="@+id/btnPlay"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="듣기"
            android:layout_marginRight="5dp"
            android:backgroundTint="@color/purple_200"/>
        <Button
            android:id="@+id/btnPause"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="일시정지"
            android:layout_marginRight="5dp"
            android:backgroundTint="@color/purple_200"/>
        <Button
            android:id="@+id/btnStop"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="중지"
            android:layout_marginLeft="5dp"
            android:backgroundTint="@color/purple_200"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:gravity="center_vertical">
        <TextView
            android:id="@+id/textView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="invisible"/>
    </LinearLayout>

</LinearLayout>

   * AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_MEDIA_AUDIO"/>

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Project13_1"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

   * MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    ListView listView;
    Button btnPlay, btnStop, btnPause;
    TextView textView;
    ProgressBar progressBar;
    List<String> list = new ArrayList<>();
    String selectedFile = list.get(0);
    MediaPlayer player = new MediaPlayer();
    boolean isPause;

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

        // external storage 읽기를 위한 코드
        ActivityCompat.requestPermissions(this,
                new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.READ_MEDIA_AUDIO}, MODE_PRIVATE);

        setUI();
        setListener();
        setList();

        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                            android.R.layout.simple_list_item_single_choice, list);
        listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
        listView.setAdapter(adapter);
        listView.setItemChecked(0, true);
    }

    private void setList() { // sd카드에 있는 mp3 파일명을 list에 담기
//        String mp3Path = Environment.getExternalStorageDirectory().getPath() + "/Music";
        String mp3Path = "/sdcard/Music";
        File file = new File(mp3Path);
        File[] files = file.listFiles(); // 해당 경로에 있는 파일 전체 가져오기
        for (File aFile : files) {
            String filename = aFile.getName();
            if (checkExt(filename)) list.add(filename);
        }
        Collections.sort(list);
//        Log.d("mytag", list.toString());
    }

    private boolean checkExt(String filename) {
        int extIndex = filename.lastIndexOf(".");
        String ext = filename.substring(extIndex + 1);
        if (ext.equals("mp3")) return true;
        return false;
    }

    private void setListener() {
        btnPlay.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        btnPause.setOnClickListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                Log.d("mytag", "i:" + i + ", l: " + l);
                selectedFile = list.get(i);
            }
        });
    }

    private void setUI() {
        listView = findViewById(R.id.listView);
        btnPlay = findViewById(R.id.btnPlay);
        btnStop = findViewById(R.id.btnStop);
        btnPause = findViewById(R.id.btnPause);
        textView = findViewById(R.id.textView);
        progressBar = findViewById(R.id.progressBar);
    }

    @Override
    public void onClick(View view) {
        if (view == btnPlay) {
            try {
                player.setDataSource("/sdcard/Music/" + selectedFile);
                player.prepare(); // 파일을 읽을 준비(메모리에 올림)
                player.start();
                progressBar.setVisibility(View.VISIBLE);
            } catch (Exception e) {
                e.printStackTrace();
            }
            textView.setText("실행중인 음악 : " + selectedFile);
        } else if (view == btnStop) {
            player.stop();
            player.reset(); // 파일을 메모리에서 제거
            progressBar.setVisibility(View.INVISIBLE);
            textView.setText("현재 재생중이 아님");
        } else if (view == btnPause) {
            if (isPause) {
                player.start();
                btnPause.setText("일시정지");
                isPause = false;
                progressBar.setVisibility(View.VISIBLE);
            }
            else {
                player.pause();
                btnPause.setText("다시 재생");
                isPause = true;
                progressBar.setVisibility(View.INVISIBLE);
            }
        }
    }
}

 

 

5. Thread

 - 여러 작업을 동시에 수행하도록 함(하나의 작업이 끝나기 전에 다른 작업을 동시에 진행시킬 수 있음)

 - Thread 연습

   * activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:padding="20dp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="1번 진행률 : 10%"
        android:layout_marginLeft="135dp"/>
    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="10"
        android:layout_marginBottom="20dp"/>
    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="2번 진행률 : 30%"
        android:layout_marginLeft="135dp"/>
    <SeekBar
        android:id="@+id/seekBar2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="30"
        android:layout_marginBottom="30dp"/>
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="스레드 시작"
        android:backgroundTint="#A1A0A0"/>

</LinearLayout>

   * MainActivity.java

public class MainActivity extends AppCompatActivity {

    SeekBar seekBar1, seekBar2;
    Button button;
    Thread thread;
    TextView textView1, textView2;

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

        seekBar1 = findViewById(R.id.seekBar1);
        seekBar2 = findViewById(R.id.seekBar2);
        button = findViewById(R.id.button);
        textView1 = findViewById(R.id.textView1);
        textView2 = findViewById(R.id.textView2);

        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 0.1초 간격으로 값을 각각 2, 1씩 증가
                for (int i = 0; i < 100; i++) {
                    int progress1 = seekBar1.getProgress() + 2;
                    if (progress1 > seekBar1.getMax()) progress1 = seekBar1.getMax();
                    int progress2 = seekBar2.getProgress() + 1;
                    if (progress2 > seekBar2.getMax()) progress2 = seekBar2.getMax();

                    seekBar1.setProgress(progress1);
                    seekBar2.setProgress(progress2);
                    SystemClock.sleep(100);

                    textView1.setText("1번 진행률 : " + progress1 + "%");
                    textView2.setText("2번 진행률 : " + progress2 + "%");
                }
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                thread.start();
            }
        });
    }
}

 

'Daily Record' 카테고리의 다른 글

6월 4주차 학습 내용 정리  (0) 2023.07.04
6월 3주차 학습 내용 정리  (0) 2023.06.25
6월 1주차 학습 내용 정리  (0) 2023.06.04
5월 4주차 학습 내용 정리  (0) 2023.05.29
5월 23일 학습 내용 정리  (0) 2023.05.23
Contents

Copied URL!

Liked this Posting!