2010. 3. 23. 09:02

Dialog App





1. Activity를 Dialog화

   다양한 형태의 UI화면을 만들고 다이얼로그로 변경하는 방법  1) 기존 Activity를 만든다.


  2) AndroidManifest.xml에 Activity를 등록할때 다음 사항을 추가한다.

   android:theme="@android:style/Theme.Dialog"

  1. <activity 
  2. android:name=".dictionary.FindWord"
  3. android:theme="@android:style/Theme.Dialog"
  4. />

 

Dialog App 예제


Text OK Cancel
List
Progress Dialog
Radiobutton Dialog
Checkbok Dialog
Password Dialog

이런 Dialog은 


파일명: Layout

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

<!-- Demonstrates different uses of the android.app.AlertDialog.
     See corresponding Java code com.example.android.apis.app.AlertDialogSamples.java. -->

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/screen"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:orientation="vertical">
        <Button android:id="@+id/two_buttons"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:text="@string/alert_dialog_two_buttons"/>
        <Button android:id="@+id/two_buttons2"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:text="@string/alert_dialog_two_buttons2"/>
        <Button android:id="@+id/select_button"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:text="@string/alert_dialog_select_button"/>
        <Button android:id="@+id/progress_button"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:text="@string/alert_dialog_progress_button"/>
        <Button android:id="@+id/radio_button"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:text="@string/alert_dialog_single_choice"/>
        <Button android:id="@+id/checkbox_button"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:text="@string/alert_dialog_multi_choice"/>
        <Button android:id="@+id/text_entry_button"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:text="@string/alert_dialog_text_entry"/>
    </LinearLayout>
</ScrollView>


파일명: AlertDialogSamples.java


package my.dia;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


// 버턴을 상수값으로 지정했다. 
public class AlertDialogSamplesextends Activity{
    private static final int DIALOG_YES_NO_MESSAGE = 1;
    private static final int DIALOG_YES_NO_LONG_MESSAGE = 2;
    private static final int DIALOG_LIST = 3;
    private static final int DIALOG_PROGRESS = 4;
    private static final int DIALOG_SINGLE_CHOICE = 5;
    private static final int DIALOG_MULTIPLE_CHOICE = 6;
    private static final int DIALOG_TEXT_ENTRY = 7;

    private static final int MAX_PROGRESS = 100;
 
    private ProgressDialog mProgressDialog;
    private int mProgress;
    private Handler mProgressHandler;

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {

        case DIALOG_YES_NO_MESSAGE:

1yesnodialog.PNG

 


            return new AlertDialog.Builder(AlertDialogSamples.this)  //이너클래스 this는 안에것이기에 밖에 것의 this를 호출하기 AlertDialogSamples.this 이렇게 한다.
                .setIcon(R.drawable.alert_dialog_icon) //new한 객체.setIcon이렇게.. "."앞에는 AlertDialog.Builder이 있는 것이다.
 
                .setTitle(R.string.alert_dialog_two_buttons_title)  // "." 앞은 AlertDialog.Builder 이 있는 것이다.
// "." 앞은 AlertDialog.Builder 이 있는 것이다. setPositiveButton OK 버턴에 할당 확인 등등
// DialogInterface.OnClickListener 이것이 핸들러이다. 

                .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { 
                    public void onClick(DialogInterface dialog, int whichButton) {
// 버턴클릭되었을때 처리할 내용 입력
                        /* User clicked OK so do some stuff */
                    }
                })
// "." 앞은 AlertDialog.Builder 이 있는 것이다. setPositiveButton취소 버턴이 할당
//
                . setPositiveButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked Cancel so do some stuff */
                    }
                })
                .create();
        case DIALOG_YES_NO_LONG_MESSAGE:

2text.PNG

 


            return new AlertDialog.Builder(AlertDialogSamples.this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(R.string.alert_dialog_two_buttons_msg)
                .setMessage(R.string.alert_dialog_two_buttons2_msg)
                .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
 
                        /* User clicked OK so do some stuff */
                    }
                })
                .setNeutralButton(R.string.alert_dialog_something, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked Something so do some stuff */
                    }
                })
                .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked Cancel so do some stuff */
                    }
                })
                .create();

        case DIALOG_LIST:

3list.PNG

 


            return new AlertDialog.Builder(AlertDialogSamples.this)
                .setTitle(R.string.select_dialog)
                .setItems(R.array.select_dialog_items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        /* User clicked so do some stuff */
                        String[] items = getResources().getStringArray(R.array.select_dialog_items);  // R.array.xml에 관련 내용이 등록되어 있음
                        new AlertDialog.Builder(AlertDialogSamples.this)
                                .setMessage("You selected: " + which + " , " + items[which])  // which값이 선택되어져서 오고 출력한다.
                                .show();
                    }
                })
                .create();

        case DIALOG_PROGRESS:

4progress.PNG

 


            mProgressDialog = new ProgressDialog(AlertDialogSamples.this);
            mProgressDialog.setIcon(R.drawable.alert_dialog_icon);
            mProgressDialog.setTitle(R.string.select_dialog);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMax(MAX_PROGRESS);  //Max값 100
// setButton을 추가한 만큼 버턴은 추가될 수 있다. 
            mProgressDialog.setButton(getText(R.string.alert_dialog_hide), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked Yes so do some stuff */
                }
            });
            mProgressDialog.setButton2(getText(R.string.alert_dialog_cancel), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked No so do some stuff */
                }
            });
            return mProgressDialog;

        case DIALOG_SINGLE_CHOICE:

5single.PNG

 


            return new AlertDialog.Builder(AlertDialogSamples.this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(R.string.alert_dialog_single_choice)
                .setSingleChoiceItems(R.array.select_dialog_items2, 0, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked on a radio button do some stuff */
                    }
                })
                .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked Yes so do some stuff */
                    }
                })
                .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked No so do some stuff */
                    }
                })
               .create();

        case DIALOG_MULTIPLE_CHOICE:

6repeat.PNG

 


            return new AlertDialog.Builder(AlertDialogSamples.this)
                .setIcon(R.drawable.ic_popup_reminder)
                .setTitle(R.string.alert_dialog_multi_choice)
                .setMultiChoiceItems(R.array.select_dialog_items3,
                        new boolean[]{false, true, false, true, false, false, false},
                        new DialogInterface.OnMultiChoiceClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton,
                                    boolean isChecked) {

                                /* User clicked on a check box do some stuff */
                            }
                        })
                .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked Yes so do some stuff */
                    }
                })
                .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked No so do some stuff */
                    }
                })
               .create();

        case DIALOG_TEXT_ENTRY:

7textentry(1).PNG

 


            // This example shows how to add a custom layout to an AlertDialog
            LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
            return new AlertDialog.Builder(AlertDialogSamples.this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(R.string.alert_dialog_text_entry)
                .setView(textEntryView)
                .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
 
                        /* User clicked OK so do some stuff */
                    }
                })
                .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked cancel so do some stuff */
                    }
                })
                .create();
        }
        return null;
    }

    /**
     * Initialization of the Activity after it is first created.  Must at least
     * call {@link android.app.Activity#setContentView(int)} to
     * describe what is to be displayed in the screen.
     */
    @Override
protected void onCreate(Bundle savedInstanceState) {  // Activity에 의해서 첫 시작한다.
        super.onCreate(savedInstanceState);

        setContentView(R.layout.alert_dialog);
 
        /* Display a text message with yes/no buttons and handle each message as well as the cancel action */
        Button twoButtonsTitle = (Button) findViewById(R.id.two_buttons);
        twoButtonsTitle.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_YES_NO_MESSAGE);  //상수값으로 어떤 것이 눌렸는지 구분해 준다. 이것을 부르는 순간에 onCreateDialog가 호출되어진다.
            }
        });
 
        /* Display a long text message with yes/no buttons and handle each message as well as the cancel action */
        Button twoButtons2Title = (Button) findViewById(R.id.two_buttons2);
        twoButtons2Title.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_YES_NO_LONG_MESSAGE);
            }
        });
 
 
        /* Display a list of items */
        Button selectButton = (Button) findViewById(R.id.select_button);
        selectButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_LIST);
            }
        });
 
        /* Display a custom progress bar */
        Button progressButton = (Button) findViewById(R.id.progress_button);
        progressButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_PROGRESS); //프로그레스 값을 초기화하게 아래에 붙은다.
                mProgress = 0;
                mProgressDialog.setProgress(0);
                mProgressHandler.sendEmptyMessage(0);
            }
        });
 
        /* Display a radio button group */
        Button radioButton = (Button) findViewById(R.id.radio_button);
        radioButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_SINGLE_CHOICE);
            }
        });
 
        /* Display a list of checkboxes */
        Button checkBox = (Button) findViewById(R.id.checkbox_button);
        checkBox.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_MULTIPLE_CHOICE);
            }
        });
 
        /* Display a text entry dialog */
        Button textEntry = (Button) findViewById(R.id.text_entry_button);
        textEntry.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_TEXT_ENTRY);
            }
        });
 
        mProgressHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (mProgress >= MAX_PROGRESS) {
                    mProgressDialog.dismiss();
                } else {
                    mProgress++;
                    mProgressDialog.incrementProgressBy(1);
                    mProgressHandler.sendEmptyMessageDelayed(0, 100);
                }
            }
        };
    }
}

파일명: arrary.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<resources>
    <!-- Used in View/Spinner1.java -->
    <string-array name="colors">
        <item>red</item>
        <item>orange</item>
        <item>yellow</item>
        <item>green</item>
        <item>blue</item>
        <item>violet</item>
    </string-array>
 
    <!-- Used in View/Spinner1.java -->
    <string-array name="planets">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
        <item>Pluto</item>
    </string-array>

    <!-- Used in App/SearchInvoke.java -->
    <string-array name="search_menuModes">
        <item>Search Key</item>
        <item>Menu Item</item>
        <item>Type-To-Search</item>
        <item>Disabled</item>
    </string-array>
 
    <!-- Used in app/dialog examples -->
    <string-array name="select_dialog_items">  //DIALOG_LIST에서 데이터를 가져가서 사용함
        <item>Command one</item>
        <item>Command two</item>
        <item>Command three</item>
        <item>Command four</item>
    </string-array>
 
    <string-array name="select_dialog_items2">
        <item>Map</item>
        <item>Satellite</item>
        <item>Traffic</item>
        <item>Street view</item>
    </string-array>
 
    <string-array name="select_dialog_items3">
        <item>Every Monday</item>
        <item>Every Tuesday</item>
        <item>Every Wednesday</item>
        <item>Every Thursday</item>
        <item>Every Friday</item>
        <item>Every Saturday</item>
        <item>Every Sunday</item>
    </string-array>
 
    <!-- Used in app/menu examples -->
    <string-array name="entries_list_preference">
        <item>Alpha Option 01</item>
        <item>Beta Option 02</item>
        <item>Charlie Option 03</item>  
    </string-array>

    <!-- Used in app/menu examples -->
    <string-array name="entryvalues_list_preference">
        <item>alpha</item>
        <item>beta</item>
        <item>charlie</item>  
    </string-array>
 
</resources>

파일명: R.String.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MyActivity!</string>
    <string name="app_name">MyDialogApp</string>
    <string name="activity_dialog">App/Activity/Dialog</string>
    <string name="dialog_activity_text">Example of how you can use the
            Theme.Dialog theme to make an activity that looks like a
            dialog.</string>

    <string name="activity_custom_dialog">App/Activity/Custom Dialog</string>
    <string name="custom_dialog_activity_text">Example of how you can use a
            custom Theme.Dialog theme to make an activity that looks like a
            customized dialog, here with an ugly frame.</string>
               <!-- ============================== -->
    <!--  app/dialog examples strings  -->
    <!-- ============================== -->

    <string name="activity_alert_dialog">App/Dialog</string>
    <string name="alert_dialog_two_buttons">OK Cancel dialog with a message</string>
    <string name="alert_dialog_two_buttons2">OK Cancel dialog with a long message</string>
    <string name="alert_dialog_select_button">List dialog</string>
    <string name="alert_dialog_single_choice">Single choice list</string>
    <string name="alert_dialog_multi_choice">Repeat alarm</string>
    <string name="alert_dialog_progress_button">Progress dialog</string>
    <string name="alert_dialog_text_entry">Text Entry dialog</string>
    <string name="alert_dialog_username">Name:</string>
    <string name="alert_dialog_password">Password:</string>
    <string name="alert_dialog_two_buttons_title">
        Lorem ipsum dolor sit aie consectetur adipiscing\nPlloaso mako nuto
        siwuf cakso dodtos anr koop.
    </string>
    <string name="alert_dialog_two_buttons_msg">Header title</string>
    <string name="alert_dialog_two_buttons2_msg">
        Plloaso mako nuto siwuf cakso dodtos anr koop a
        cupy uf cak vux noaw yerw phuno. Whag schengos, uf efed, quiel
        ba mada su otrenzr.\n\nSwipontgwook proudgs hus yag su ba dagarmidad.
        Plasa maku noga wipont trenzsa schengos ent kaap zux comy.\n\nWipont trenz
        kipg naar mixent phona. Cak pwico siructiun
        ruous nust apoply tyu cak Uhex sisulutiun munityuw uw dseg
    </string>
    <string name="alert_dialog_ok">OK</string>
    <string name="alert_dialog_hide">Hide</string>
    <string name="alert_dialog_something">Something</string>
    <string name="alert_dialog_cancel">Cancel</string>
    <string name="alert_dialog_progress_text1">34</string>
    <string name="alert_dialog_progress_text2">145/305 KB</string>

    <string name="select_dialog">Header title</string>
    <string name="select_dialog_show">List dialog</string>
 
</resources>


이후 강의 내용

알람 처리



package service.alarm;


import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import java.util.Calendar;

/**
 * Example of scheduling one-shot and repeating alarms.  See
 * {@link OneShotAlarm} for the code run when the one-shot alarm goes off, and
 * {@link RepeatingAlarm} for the code run when the repeating alarm goes off.
 * <h4>Demo</h4>
App/Service/Alarm Controller
 
<h4>Source files</h4>
<table class="LinkTable">
        <tr>
            <td class="LinkColumn">src/com.example.android.apis/app/AlarmController.java</td>
            <td class="DescrColumn">The activity that lets you schedule alarms</td>
        </tr>
        <tr>
            <td class="LinkColumn">src/com.example.android.apis/app/OneShotAlarm.java</td>
            <td class="DescrColumn">This is an intent receiver that executes when the
                one-shot alarm goes off</td>
        </tr>
        <tr>
            <td class="LinkColumn">src/com.example.android.apis/app/RepeatingAlarm.java</td>
            <td class="DescrColumn">This is an intent receiver that executes when the
                repeating alarm goes off</td>
        </tr>
        <tr>
            <td class="LinkColumn">/res/any/layout/alarm_controller.xml</td>
            <td class="DescrColumn">Defines contents of the screen</td>
        </tr>
</table>

 */
public class AlarmController extends Activity {
    Toast mToast;

    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.alarm_controller);

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.one_shot);
        button.setOnClickListener(mOneShotListener);
        button = (Button)findViewById(R.id.start_repeating);
        button.setOnClickListener(mStartRepeatingListener);
        button = (Button)findViewById(R.id.stop_repeating);
        button.setOnClickListener(mStopRepeatingListener);
    }

    private OnClickListener mOneShotListener = new OnClickListener() {
        public void onClick(View v) {
            // When the alarm goes off, we want to broadcast an Intent to our
            // BroadcastReceiver.  Here we make an Intent with an explicit class
            // name to have our own receiver (which has been published in
            // AndroidManifest.xml) instantiated and called, and then create an
            // IntentSender to have the intent executed as a broadcast.
            Intent intent = new Intent(AlarmController.this, OneShotAlarm.class);
            PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this,
                    0, intent, 0);

            // We want the alarm to go off 30 seconds from now.
            Calendar calendar = Calendar.getInstance();  //켈린터 객체 세팅
            calendar.setTimeInMillis(System.currentTimeMillis()); // 현재 시간 세팅
            calendar.add(Calendar.SECOND, 30); // 30초를 추가한다 30초 후 진행

            // Schedule the alarm!
            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);  // 메지저는 프레임이 가지고 있다. 
            am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);  // Set을 한다. 센더(인텐트)를 깨운다. 팬딩인텐트를 30초후에 깨운다. 불러줘라

            // Tell the user about what we did.
            if (mToast != null) {
                mToast.cancel();
            }
            mToast = Toast.makeText(AlarmController.this, R.string.one_shot_scheduled,   //일단 알람메니저에게 30초 깨우는 것 등록후 나는 토스트로 문자열을 뜨워줄 것이다. 
                    Toast.LENGTH_LONG);

 


            mToast.show();
8알람oneshot.PNG

 


        }
    };

    private OnClickListener mStartRepeatingListener= new OnClickListener() {
        public void onClick(View v) {
            // When the alarm goes off, we want to broadcast an Intent to our
            // BroadcastReceiver.  Here we make an Intent with an explicit class
            // name to have our own receiver (which has been published in
            // AndroidManifest.xml) instantiated and called, and then create an
            // IntentSender to have the intent executed as a broadcast.
            // Note that unlike above, this IntentSender is configured to
            // allow itself to be sent multiple times.
            Intent intent = new Intent(AlarmController.this, RepeatingAlarm.class);
            PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this,
                    0, intent, 0);
 
            // We want the alarm to go off 30 seconds from now.
            long firstTime = SystemClock.elapsedRealtime();  // 부팅후 얼마의 시간 경과 시간을 뜻한다. 결국 현재 시간과 똑같다
            firstTime += 15*1000; // 밀리센컨드로 천을 콥하니 15초후를 구한 것이다. 

            // Schedule the alarm!
            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);  // 알람 메니저를 꺼내서 set리피팅
            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, // 반복해라라고 요청한다. 지금으로부터 15초후 15초 간경으로 센더(브로드케스팅)을 수행하게 된다.
                            firstTime, 15*1000, sender);

            // Tell the user about what we did.
            if (mToast != null) {  // 토스트가 널이 아니면 다시 시작해라
                mToast.cancel();
            }
            mToast = Toast.makeText(AlarmController.this, R.string.repeating_scheduled,
                    Toast.LENGTH_LONG);

            mToast.show();

9알람.PNG

 


        }
    };

    private OnClickListener mStopRepeatingListener= new OnClickListener() {
        public void onClick(View v) {
            // Create the same intent, and thus a matching IntentSender, for
            // the one that was scheduled.
            Intent intent = new Intent(AlarmController.this, RepeatingAlarm.class);
            PendingIntent sender = PendingIntent.getBroadcast(AlarmController.this,
                    0, intent, 0);
 
            // And cancel the alarm.
            AlarmManageram = (AlarmManager)getSystemService(ALARM_SERVICE);
            am.cancel(sender);

            // Tell the user about what we did.
            if (mToast != null) {
                mToast.cancel();
            }
            mToast = Toast.makeText(AlarmController.this, R.string.repeating_unscheduled,
                    Toast.LENGTH_LONG);
            mToast.show();
        }
    };
}

// 리시버는 종료가 필요하지 않다. 

package service.alarm;

import android.content.Context;
import android.content.Intent;
import android.content.BroadcastReceiver;
import android.widget.Toast;



/**
 * This is an example of implement an {@link BroadcastReceiver} for an alarm that
 * should occur once.
 * <p>
 * When the alarm goes off, we show a <i>Toast</i>, a quick message.
 */
public class OneShotAlarm extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context, R.string.one_shot_received, Toast.LENGTH_SHORT).show();
    }
}

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package service.alarm;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.


import android.content.Context;
import android.content.Intent;
import android.content.BroadcastReceiver;
import android.widget.Toast;

/**
 * This is an example of implement an {@link BroadcastReceiver} for an alarm that
 * should occur once.
 */
public class RepeatingAlarmextends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {

        Toast.makeText(context, R.string.repeating_received, Toast.LENGTH_SHORT).show();  //여기에다 미디어 플레이 사용하면 소리가 나온다. 

10리피팅알람.PNG

 

//을 알람메니저가 이 onReceive를 호출해 주기때문에 토스트가 표시된 것이다.


    }
}

프리퍼런스

값을 수정해서 프로그램 종료하거나 전원을 off후 on하고 다시 실행해도 이전 값이 남아 있는다. xml에 값을 저장하게 된다.
재배포시에 아마도 지워 초기화 될 것이다.
이것은 UI 자체에 저장기능을 사용하는 것이다. 
 - preferencefrom xml java하나 가 돈다 이것이 저장하고 있는 것이다.
주로 체크박스에 많이 사용한다. 



AdvancedPreferences
DefaultValues
LaunchingPreferences
PreferenceDependencies
PreferencesFromCode

파일명: PreferencesFromXml


package my.pref;



import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;

public class PreferencesFromXml extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences); //R에서 갔다 쓸 것이다.
    }

}

파일명: preferences.xml

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

<!-- This is a primitive example showing the different types of preferences available. -->
<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory  // 이 것 처럼 일반 UI가 아니라 프리퍼런스UI를 사용해야만 값을 저장할 수 있는 것이다. 
//이것은    addPreferencesFromResource(R.xml.preferences); 으로부터 호출되어 지는 것이다.
            android:title="@string/inline_preferences">
 
        <CheckBoxPreference // 이 것을 사용해서 저장할 수 있는 것이다.
                android:key="checkbox_preference"
                android:title="@string/title_toggle_preference"
                android:summary="@string/summary_toggle_preference" />
 
    </PreferenceCategory>
 
    <PreferenceCategory
            android:title="@string/dialog_based_preferences">

        <EditTextPreference
                android:key="edittext_preference"
                android:title="@string/title_edittext_preference"
                android:summary="@string/summary_edittext_preference"
                android:dialogTitle="@string/dialog_title_edittext_preference" />
 
        <ListPreference
                android:key="list_preference"
                android:title="@string/title_list_preference"
                android:summary="@string/summary_list_preference"
                android:entries="@array/entries_list_preference"
                android:entryValues="@array/entryvalues_list_preference"
                android:dialogTitle="@string/dialog_title_list_preference" />

    </PreferenceCategory>

    <PreferenceCategory
            android:title="@string/launch_preferences">

        <!-- This PreferenceScreen tag serves as a screen break (similar to page break
             in word processing). Like for other preference types, we assign a key
             here so it is able to save and restore its instance state. -->
        <PreferenceScreen  // 이 것때문에 새로운 창이 뜨게 된다. 스크린안에 스크린을 넣었기에 새로운 창이 열리는 것이다. 
                android:key="screen_preference"
                android:title="@string/title_screen_preference"
                android:summary="@string/summary_screen_preference">
 
            <!-- You can place more preferences here that will be shown on the next screen. -->
 
            <CheckBoxPreference
                    android:key="next_screen_checkbox_preference"
                    android:title="@string/title_next_screen_toggle_preference"
                    android:summary="@string/summary_next_screen_toggle_preference" />
 
        </PreferenceScreen>

        <PreferenceScreen
                android:title="@string/title_intent_preference"
                android:summary="@string/summary_intent_preference">

            <intentandroid:action="android.intent.action.VIEW"    // 인텐트에 값을 넣어서 URL값을 전달한다. 
                    android:data="http://www.android.com" />

        </PreferenceScreen>

    </PreferenceCategory>
 
    <PreferenceCategory
            android:title="@string/preference_attributes">
 
        <CheckBoxPreference
                android:key="parent_checkbox_preference"
                android:title="@string/title_parent_preference"
                android:summary="@string/summary_parent_preference" />

        <!-- The visual style of a child is defined by this styled theme attribute. -->
        <CheckBoxPreference
                android:key="child_checkbox_preference"
                android:dependency="parent_checkbox_preference"
                android:layout="?android:attr/preferenceLayoutChild"
                android:title="@string/title_child_preference"
                android:summary="@string/summary_child_preference" />
 
    </PreferenceCategory>
 
</PreferenceScreen>

파일명: array.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<resources>
    <!-- Used in View/Spinner1.java -->
    <string-array name="colors">
        <item>red</item>
        <item>orange</item>
        <item>yellow</item>
        <item>green</item>
        <item>blue</item>
        <item>violet</item>
    </string-array>
 
    <!-- Used in View/Spinner1.java -->
    <string-array name="planets">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
        <item>Pluto</item>
    </string-array>

    <!-- Used in App/SearchInvoke.java -->
    <string-array name="search_menuModes">
        <item>Search Key</item>
        <item>Menu Item</item>
        <item>Type-To-Search</item>
        <item>Disabled</item>
    </string-array>
 
    <!-- Used in app/dialog examples -->
    <string-array name="select_dialog_items">
        <item>Command one</item>
        <item>Command two</item>
        <item>Command three</item>
        <item>Command four</item>
    </string-array>
 
    <string-array name="select_dialog_items2">
        <item>Map</item>
        <item>Satellite</item>
        <item>Traffic</item>
        <item>Street view</item>
    </string-array>
 
    <string-array name="select_dialog_items3">
        <item>Every Monday</item>
        <item>Every Tuesday</item>
        <item>Every Wednesday</item>
        <item>Every Thursday</item>
        <item>Every Friday</item>
        <item>Every Saturday</item>
        <item>Every Sunday</item>
    </string-array>
 
    <!-- Used in app/menu examples --> // 선택되면 보여지는 것이고 값을 수정하면 아랬것으로 저장한다. 
    <string-array name="entries_list_preference"> 
        <item>Alpha Option 01</item>
        <item>Beta Option 02</item>
        <item>Charlie Option 03</item>  
    </string-array>

    <!-- Used in app/menu examples -->   // 이것에 저장하겠다. 상기에 것은 보이는 것
    <string-array name="entryvalues_list_preference">
        <item>alpha</item>
        <item>beta</item>
        <item>charlie</item>  
    </string-array>
 
</resources>

데이터는 아래 위치에 저장된다.

11preference.PNG