Views_Animation_Shake

old/API_Demo 2010. 3. 26. 13:46

[Animation1.java]

import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

public class Animation1 extends Activity implements View.OnClickListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.animation_1);

        View loginButton = findViewById(R.id.login);
        loginButton.setOnClickListener(this);
    }

    public void onClick(View v) {
        Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
        findViewById(R.id.pw).startAnimation(shake);

    }

}

'old > API_Demo' 카테고리의 다른 글

View_AutoComplete_ScreenBottom  (0) 2010.04.02
View_AutoComplete_ScreenTop  (0) 2010.04.02
Views_Animation_Push  (0) 2010.03.26
Views_Animation_Interpolators  (0) 2010.03.26
Views_Animation_3DTransition  (0) 2010.03.26
Posted by jazzlife
,

Views_Animation_Push

old/API_Demo 2010. 3. 26. 11:09

[Animation2.java]

import android.view.animation.AnimationUtils;
import android.widget.ViewFlipper;


public class Animation2 extends Activity implements
        AdapterView.OnItemSelectedListener
{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.animation_2);

        mFlipper = ((ViewFlipper) this.findViewById(R.id.flipper));
        mFlipper.startFlipping();

        Spinner s = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, mStrings);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(adapter);
        s.setOnItemSelectedListener(this);
    }

    public void onItemSelected(AdapterView parent, View v, int position, long id) {
        switch (position) {

        case 0:
            mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_up_in));
            mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_up_out));
            break;
        case 1:
            mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_left_in));
            mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.push_left_out));
            break;
        case 2:
            mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
                    android.R.anim.fade_in));
            mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                    android.R.anim.fade_out));
            break;
        default:
            mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.hyperspace_in));
            mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
                    R.anim.hyperspace_out));
            break;
        }
    }

    public void onNothingSelected(AdapterView parent) {
    }

    private String[] mStrings = {
            "Push up", "Push left", "Cross fade", "Hyperspace"};

    private ViewFlipper mFlipper;

}



[animation_2.xml]

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:padding="10dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

    <ViewFlipper android:id="@+id/flipper"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:flipInterval="2000"
                android:layout_marginBottom="20dip" >
                <TextView
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_horizontal"
                        android:textSize="26sp"
                        android:text="@string/animation_2_text_1"/>
                <TextView
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_horizontal"
                        android:textSize="26sp"
                        android:text="@string/animation_2_text_2"/>
                <TextView
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_horizontal"
                        android:textSize="26sp"
                        android:text="@string/animation_2_text_3"/>
                <TextView
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center_horizontal"
                        android:textSize="26sp"
                        android:text="@string/animation_2_text_4"/>
    </ViewFlipper>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dip"
        android:text="@string/animation_2_instructions"
    />

    <Spinner android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />

</LinearLayout>


 [push_up_in.xml]

<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="300"/>
 <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>


[push_up_out.xml]

<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="0" android:toYDelta="-100%p" android:duration="300"/>
 <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="300" />
</set>

[push_left_in.xml]

<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="300"/>
 <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" />
</set>

[push_left_out.xml]

<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromXDelta="0" android:toXDelta="-100%p" android:duration="300"/>
 <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="300" />
</set>


[hyperspace_in.xml]

<alpha xmlns:android="http://schemas.android.com/apk/res/android" android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="300" android:startOffset="1200" />



[hyperspace_out.xml]

<set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false">

 <scale
  android:interpolator="@android:anim/accelerate_decelerate_interpolator"
  android:fromXScale="1.0"
  android:toXScale="1.4"
  android:fromYScale="1.0"
  android:toYScale="0.6"
  android:pivotX="50%"
  android:pivotY="50%"
  android:fillAfter="false"
  android:duration="700" />


 <set
  android:interpolator="@android:anim/accelerate_interpolator"
                android:startOffset="700">
 
  <scale
   android:fromXScale="1.4"
   android:toXScale="0.0"
          android:fromYScale="0.6"
    android:toYScale="0.0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="400" />
   
  <rotate
   android:fromDegrees="0"
   android:toDegrees="-45"
    android:toYScale="0.0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="400" />
 </set>

</set>

'old > API_Demo' 카테고리의 다른 글

View_AutoComplete_ScreenTop  (0) 2010.04.02
Views_Animation_Shake  (0) 2010.03.26
Views_Animation_Interpolators  (0) 2010.03.26
Views_Animation_3DTransition  (0) 2010.03.26
Text_LogTextBox  (0) 2010.03.25
Posted by jazzlife
,

[Animation3.java]

public class Animation3 extends Activity implements AdapterView.OnItemSelectedListener {
    private static final String[] INTERPOLATORS = {
            "Accelerate", "Decelerate", "Accelerate/Decelerate",
            "Anticipate", "Overshoot", "Anticipate/Overshoot",
            "Bounce"
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.animation_3);

        Spinner s = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, INTERPOLATORS);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s.setAdapter(adapter);
        s.setOnItemSelectedListener(this);
    }

    public void onItemSelected(AdapterView parent, View v, int position, long id) {
        final View target = findViewById(R.id.target);
        final View targetParent = (View) target.getParent();

        Animation a = new TranslateAnimation(0.0f,
                targetParent.getWidth() - target.getWidth() - targetParent.getPaddingLeft() -
                targetParent.getPaddingRight(), 0.0f, 0.0f);
        a.setDuration(1000);
        a.setStartOffset(300);
        a.setRepeatMode(Animation.RESTART);
        a.setRepeatCount(Animation.INFINITE);

        switch (position) {
            case 0:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.accelerate_interpolator));
                break;
            case 1:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.decelerate_interpolator));
                break;
            case 2:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.accelerate_decelerate_interpolator));
                break;
            case 3:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.anticipate_interpolator));
                break;
            case 4:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.overshoot_interpolator));
                break;
            case 5:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.anticipate_overshoot_interpolator));
                break;
            case 6:
                a.setInterpolator(AnimationUtils.loadInterpolator(this,
                        android.R.anim.bounce_interpolator));
                break;
        }

        target.startAnimation(a);
    }

    public void onNothingSelected(AdapterView parent) {
    }



[animation_3.xml]

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:clipToPadding="false">

    <TextView
        android:id="@+id/target"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="26sp"
        android:text="@string/animation_3_text"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:layout_marginBottom="5dip"
        android:text="@string/animation_2_instructions" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

'old > API_Demo' 카테고리의 다른 글

Views_Animation_Shake  (0) 2010.03.26
Views_Animation_Push  (0) 2010.03.26
Views_Animation_3DTransition  (0) 2010.03.26
Text_LogTextBox  (0) 2010.03.25
Text_Linkify  (0) 2010.03.25
Posted by jazzlife
,

[Rotate3DAnimation.java]

import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.graphics.Camera;
import android.graphics.Matrix;

public class Rotate3dAnimation extends Animation {
    private final float mFromDegrees;
    private final float mToDegrees;
    private final float mCenterX;
    private final float mCenterY;
    private final float mDepthZ;
    private final boolean mReverse;
    private Camera mCamera;

     public Rotate3dAnimation(float fromDegrees, float toDegrees,
            float centerX, float centerY, float depthZ, boolean reverse) {
        mFromDegrees = fromDegrees;
        mToDegrees = toDegrees;
        mCenterX = centerX;
        mCenterY = centerY;
        mDepthZ = depthZ;
        mReverse = reverse;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        final float fromDegrees = mFromDegrees;
        float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        final float centerX = mCenterX;
        final float centerY = mCenterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();

        camera.save();
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        camera.rotateY(degrees);
        camera.getMatrix(matrix);
        camera.restore();

        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);
    }
}



[Transition3d.java]

       private ViewGroup mContainer;

        private void applyRotation(int position, float start, float end) {
        // Find the center of the container
        final float centerX = mContainer.getWidth() / 2.0f;
        final float centerY = mContainer.getHeight() / 2.0f;

      // Create a new 3D rotation with the supplied parameter
      // The animation listener is used to trigger the next animation

        final Rotate3dAnimation rotation =
                new Rotate3dAnimation(start, end, centerX, centerY, 310.0f, true);
        rotation.setDuration(500);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(position));

        mContainer.startAnimation(rotation);
    }

    public void onItemClick(AdapterView parent, View v, int position, long id) {
        // Pre-load the image then start the animation
        mImageView.setImageResource(PHOTOS_RESOURCES[position]);
        applyRotation(position, 0, 90);
    }

    public void onClick(View v) {
        applyRotation(-1, 180, 90);
    }

    /**
     * This class listens for the end of the first half of the animation.
     * It then posts a new action that effectively swaps the views when the container
     * is rotated 90 degrees and thus invisible.
     */
    private final class DisplayNextView implements Animation.AnimationListener {
        private final int mPosition;

        private DisplayNextView(int position) {
            mPosition = position;
        }

        public void onAnimationStart(Animation animation) {
        }

        public void onAnimationEnd(Animation animation) {
            mContainer.post(new SwapViews(mPosition));
        }

        public void onAnimationRepeat(Animation animation) {
        }
    }

    /**
     * This class is responsible for swapping the views and start the second
     * half of the animation.
     */

    private final class SwapViews implements Runnable {
        private final int mPosition;

        public SwapViews(int position) {
            mPosition = position;
        }

        public void run() {
            final float centerX = mContainer.getWidth() / 2.0f;
            final float centerY = mContainer.getHeight() / 2.0f;
            Rotate3dAnimation rotation;
           
            if (mPosition > -1) {
                mPhotosList.setVisibility(View.GONE);
                mImageView.setVisibility(View.VISIBLE);
                mImageView.requestFocus();

                rotation = new Rotate3dAnimation(90, 180, centerX, centerY, 310.0f, false);
            } else {
                mImageView.setVisibility(View.GONE);
                mPhotosList.setVisibility(View.VISIBLE);
                mPhotosList.requestFocus();

                rotation = new Rotate3dAnimation(90, 0, centerX, centerY, 310.0f, false);
            }

            rotation.setDuration(500);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());

            mContainer.startAnimation(rotation);
        }
    }


'old > API_Demo' 카테고리의 다른 글

Views_Animation_Push  (0) 2010.03.26
Views_Animation_Interpolators  (0) 2010.03.26
Text_LogTextBox  (0) 2010.03.25
Text_Linkify  (0) 2010.03.25
Content_Resources_Resources  (0) 2010.03.25
Posted by jazzlife
,

Text_LogTextBox

old/API_Demo 2010. 3. 25. 19:14

[LogTextBox1.java]

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.log_text_box_1);
       
        mText = (LogTextBox) findViewById(R.id.text);
       
        Button addButton = (Button) findViewById(R.id.add);
        addButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                mText.append("This is a test\n");
            } });
    }
}



[LogTextBox.java]

public class LogTextBox extends TextView {
    public LogTextBox(Context context) {
        this(context, null);
    }

    public LogTextBox(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }

    public LogTextBox(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected MovementMethod getDefaultMovementMethod() {
        return ScrollingMovementMethod.getInstance();
    }

    @Override
    public Editable getText() {
        return (Editable) super.getText();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, BufferType.EDITABLE);
    }
}


[log_text_box_1.xml]

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/log_text_box_1_add_text"/>

    <com.example.android.apis.text.LogTextBox
        android:id="@+id/text"
        android:background="@drawable/box"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:scrollbars="vertical"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/log_text_box_1_do_nothing_text"/>

</LinearLayout>

'old > API_Demo' 카테고리의 다른 글

Views_Animation_Interpolators  (0) 2010.03.26
Views_Animation_3DTransition  (0) 2010.03.26
Text_Linkify  (0) 2010.03.25
Content_Resources_Resources  (0) 2010.03.25
Content_Assets_ReadAsset  (0) 2010.03.25
Posted by jazzlife
,

Text_Linkify

old/API_Demo 2010. 3. 25. 19:03

[Link.java]

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

        setContentView(R.layout.link);

        TextView t2 = (TextView) findViewById(R.id.text2);
        t2.setMovementMethod(LinkMovementMethod.getInstance());

        TextView t3 = (TextView) findViewById(R.id.text3);
        t3.setText(
            Html.fromHtml(
                "<b>text3:</b>  Text with a " +
                "<a href=\"
http://www.google.com\">link</a> " +
                "created in the Java source code using HTML."));
        t3.setMovementMethod(LinkMovementMethod.getInstance());

        SpannableString ss = new SpannableString(
            "text4: Click here to dial the phone.");

        ss.setSpan(new StyleSpan(Typeface.BOLD), 0, 6,
                   Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new URLSpan("tel:4155551212"), 13, 17,
                   Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        TextView t4 = (TextView) findViewById(R.id.text4);
        t4.setText(ss);
        t4.setMovementMethod(LinkMovementMethod.getInstance());
    }



[link.xml]

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content">

  <!-- Four TextView widgets, each one displaying text containing links. -->

  <!-- text1 automatically linkifies things like URLs and phone numbers. -->
  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/text1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:autoLink="all"
            android:text="@string/link_text_auto"
            />

  <!-- text2 uses a string resource containing explicit <a> tags to
       specify links. -->
  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/text2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="@string/link_text_manual"
            />

  <!-- text3 builds the text in the Java code using HTML. -->
  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/text3"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            />

  <!-- text4 builds the text in the Java code without using HTML. -->
  <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/text4"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            />

</LinearLayout>


[strings.xml]

    <string name="link_text_auto"><b>text1:</b> This is some text.  In
      this text are some things that are actionable.  For instance,
      you can click on http://www.google.com and it will launch the
      web browser.  You can click on google.com too.  And, if you
      click on (415) 555-1212 it should dial the phone.
    </string>
    <string name="link_text_manual"><b>text2:</b> This is some other
      text, with a <a href="http://www.google.com">link</a> specified
      via an &lt;a&gt; tag.  Use a \"tel:\" URL
      to <a href="tel:4155551212">dial a phone number</a>.
    </string>

'old > API_Demo' 카테고리의 다른 글

Views_Animation_3DTransition  (0) 2010.03.26
Text_LogTextBox  (0) 2010.03.25
Content_Resources_Resources  (0) 2010.03.25
Content_Assets_ReadAsset  (0) 2010.03.25
APP_VoiceRecognition  (0) 2010.03.25
Posted by jazzlife
,

[ResourcesSample.java]

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

        // See res/any/layout/resources.xml for this view layout definition.
        setContentView(R.layout.resources);

        TextView tv;
        CharSequence cs;
        String str;

        // ====== Using the Context.getString() convenience method ===========

        // Using the getString() conevenience method, retrieve a string
        // resource that hapepns to have style information.  Note the use of
        // CharSequence instead of String so we don't lose the style info.

        cs = getText(R.string.styled_text);
        tv = (TextView)findViewById(R.id.styled_text);
        tv.setText(cs);

        // Use the same resource, but convert it to a string, which causes it
        // to lose the style information.

        str = getString(R.string.styled_text);
        tv = (TextView)findViewById(R.id.plain_text);
        tv.setText(str);

        // ====== Using the Resources object =================================
       
        // You might need to do this if your code is not in an activity.
        // For example View has a protected mContext field you can use.
        // In this case it's just 'this' since Activity is a context.

        Context context = this;

        // Get the Resources object from our context
        Resources res = context.getResources();

        // Get the string resource, like above.
        cs = res.getText(R.string.styled_text);
        tv = (TextView)findViewById(R.id.res1);
        tv.setText(cs);

        // Note that the Resources class has methods like getColor(),
        // getDimen(), getDrawable() because themes are stored in resources.
        // You can use them, but you might want to take a look at the view
        // examples to see how to make custom widgets.

    }



[strings.xml]

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
   <string name="styled_text">Plain, <b>bold</b>, <i>italic</i>, <b><i>bold-italic</i></b></string>
</resources>

'old > API_Demo' 카테고리의 다른 글

Text_LogTextBox  (0) 2010.03.25
Text_Linkify  (0) 2010.03.25
Content_Assets_ReadAsset  (0) 2010.03.25
APP_VoiceRecognition  (0) 2010.03.25
APP_TextToSpeech  (0) 2010.03.25
Posted by jazzlife
,

[ReadAsset.java]

import java.io.IOException;
import java.io.InputStream;


public class ReadAsset extends Activity
{
    @Override
 protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // See assets/res/any/layout/styled_text.xml for this
        // view layout definition.

        setContentView(R.layout.read_asset);

        // Programmatically load text from an asset and place it into the
        // text view.  Note that the text we are loading is ASCII, so we
        // need to convert it to UTF-16.
        try {
            InputStream is = getAssets().open("read_asset.txt");
           
            // We guarantee that the available method returns the total
            // size of the asset...  of course, this does mean that a single
            // asset can't be more than 2 gigs.
            int size = is.available();
           
            // Read the entire asset into a local byte buffer.
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
           
            // Convert the buffer into a string.
            String text = new String(buffer);
           
            // Finally stick the string into the text view.
            TextView tv = (TextView)findViewById(R.id.text);
            tv.setText(text);
        } catch (IOException e) {
            // Should never happen!
            throw new RuntimeException(e);
        }
    }
}



[StyledText.java]

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

        // See assets/res/any/layout/styled_text.xml for this
        // view layout definition.
        setContentView(R.layout.styled_text);

        // Programmatically retrieve a string resource with style
        // information and apply it to the second text view.  Note the
        // use of CharSequence instead of String so we don't lose
        // the style info.

        CharSequence str = getText(R.string.styled_text);
        TextView tv = (TextView)findViewById(R.id.text);
        tv.setText(str);
    }
}



[Manifest.xml]

        <activity android:name=".content.ReadAsset" android:label="@string/activity_read_asset">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.SAMPLE_CODE" />
                <category android:name="android.intent.category.EMBED" />
            </intent-filter>
        </activity>



[read_asset.xml]

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView android:id="@+id/text"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textStyle="normal"/>

</LinearLayout>



[styled_text.xml]

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/styled_text_rsrc"/>

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textStyle="normal"
        android:text="@string/styled_text"/>

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        />

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="@string/styled_text_prog"/>

    <TextView android:id="@+id/text"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textStyle="normal"/>

</LinearLayout>

'old > API_Demo' 카테고리의 다른 글

Text_Linkify  (0) 2010.03.25
Content_Resources_Resources  (0) 2010.03.25
APP_VoiceRecognition  (0) 2010.03.25
APP_TextToSpeech  (0) 2010.03.25
APP_Service_ServiceStartArgumentsController  (0) 2010.03.25
Posted by jazzlife
,

APP_VoiceRecognition

old/API_Demo 2010. 3. 25. 18:16

[VoiceRecognition.java]

import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;

public class VoiceRecognition extends Activity implements OnClickListener {
   
    private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
   
    private ListView mList;

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

        // Inflate our UI from its XML layout description.
        setContentView(R.layout.voice_recognition);

        // Get display items for later interaction
        Button speakButton = (Button) findViewById(R.id.btn_speak);
       
        mList = (ListView) findViewById(R.id.list);

        // Check to see if a recognition activity is present
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() != 0) {
            speakButton.setOnClickListener(this);
        } else {
            speakButton.setEnabled(false);
            speakButton.setText("Recognizer not present");
        }
    }

    /**
     * Handle the click on the start recognition button.
     */

    public void onClick(View v) {
        if (v.getId() == R.id.btn_speak) {
            startVoiceRecognitionActivity();
        }
    }

    /**
     * Fire an intent to start the speech recognition activity.
     */

    private void startVoiceRecognitionActivity() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
    }

    /**
     * Handle the results from the recognition activity.
     */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
            // Fill the list view with the strings the recognizer thought it could have heard
            ArrayList<String> matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                    matches));
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}

'old > API_Demo' 카테고리의 다른 글

Content_Resources_Resources  (0) 2010.03.25
Content_Assets_ReadAsset  (0) 2010.03.25
APP_TextToSpeech  (0) 2010.03.25
APP_Service_ServiceStartArgumentsController  (0) 2010.03.25
APP_Service_RemoteServiceBinding  (0) 2010.03.25
Posted by jazzlife
,

APP_TextToSpeech

old/API_Demo 2010. 3. 25. 18:13

[TextToSpeech.java]

import android.speech.tts.TextToSpeech;

   private static final String TAG = "TextToSpeechDemo";

    private TextToSpeech mTts;
    private Button mAgainButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text_to_speech);

        // Initialize text-to-speech. This is an asynchronous operation.
        // The OnInitListener (second argument) is called after initialization completes.

        mTts = new TextToSpeech(this,
            this  // TextToSpeech.OnInitListener
            );

        // The button is disabled in the layout.
        // It will be enabled upon initialization of the TTS engine.

        mAgainButton = (Button) findViewById(R.id.again_button);

        mAgainButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                sayHello();
            }
        });
    }

    @Override
    public void onDestroy() {
        // Don't forget to shutdown!
        if (mTts != null) {
            mTts.stop();
            mTts.shutdown();
        }

        super.onDestroy();
    }

    // Implements TextToSpeech.OnInitListener.
    public void onInit(int status) {

        if (status == TextToSpeech.SUCCESS) {

            int result = mTts.setLanguage(Locale.US);

            if (result == TextToSpeech.LANG_MISSING_DATA ||
                result == TextToSpeech.LANG_NOT_SUPPORTED) {

                Log.e(TAG, "Language is not available.");
            } else {

                mAgainButton.setEnabled(true);
                sayHello();
            }
        } else {
            Log.e(TAG, "Could not initialize TextToSpeech.");
        }
    }

    private static final Random RANDOM = new Random();
    private static final String[] HELLOS = {
      "Hello",
      "Salutations",
      "Greetings",
      "Howdy",
      "What's crack-a-lackin?",
      "That explains the stench!"
    };

    private void sayHello() {
        // Select a random hello.
        int helloLength = HELLOS.length;
        String hello = HELLOS[RANDOM.nextInt(helloLength)];
        mTts.speak(hello,
            TextToSpeech.QUEUE_FLUSH,  // Drop all pending entries in the playback queue.
            null);
    }

'old > API_Demo' 카테고리의 다른 글

Content_Assets_ReadAsset  (0) 2010.03.25
APP_VoiceRecognition  (0) 2010.03.25
APP_Service_ServiceStartArgumentsController  (0) 2010.03.25
APP_Service_RemoteServiceBinding  (0) 2010.03.25
APP_Service_RemoteServiceController  (0) 2010.03.25
Posted by jazzlife
,

[ServiceStartArgumentsController.java]

   private OnClickListener mStart1Listener = new OnClickListener() {
        public void onClick(View v) {
            startService(new Intent(ServiceStartArgumentsController.this,
                    ServiceStartArguments.class)
                            .putExtra("name", "One"));
        }
    };

    private OnClickListener mStart2Listener = new OnClickListener() {
        public void onClick(View v) {
            startService(new Intent(ServiceStartArgumentsController.this,
                    ServiceStartArguments.class)
                            .putExtra("name", "Two"));
        }
    };

    private OnClickListener mStart3Listener = new OnClickListener() {
        public void onClick(View v) {
            startService(new Intent(ServiceStartArgumentsController.this,
                    ServiceStartArguments.class)
                            .putExtra("name", "Three")
                            .putExtra("redeliver", true));
        }
    };

    private OnClickListener mStartFailListener = new OnClickListener() {
        public void onClick(View v) {
            startService(new Intent(ServiceStartArgumentsController.this,
                    ServiceStartArguments.class)
                            .putExtra("name", "Failure")
                            .putExtra("fail", true));
        }
    };

    private OnClickListener mKillListener = new OnClickListener() {
        public void onClick(View v) {

            Process.killProcess(Process.myPid());
        }
    };



[ServiceStartArgument.java]

public class ServiceStartArguments extends Service {
    private NotificationManager mNM;
    private Intent mInvokeIntent;
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;

   
    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

       
        @Override
        public void handleMessage(Message msg)
        {
            Bundle arguments = (Bundle)msg.obj;
       
            String txt = arguments.getString("name");
           
            Log.i("ServiceStartArguments", "Message: " + msg + ", "
                    + arguments.getString("name"));
       
            if ((msg.arg2&Service.START_FLAG_REDELIVERY) == 0) {
                txt = "New cmd #" + msg.arg1 + ": " + txt;
            } else {
                txt = "Re-delivered #" + msg.arg1 + ": " + txt;
            }
           
            showNotification(txt);
       
            // Normally we would do some work here...  for our sample, we will
            // just sleep for 5 seconds.

            long endTime = System.currentTimeMillis() + 5*1000;
            while (System.currentTimeMillis() < endTime) {
                synchronized (this) {
                    try {
                        wait(endTime - System.currentTimeMillis());
                    } catch (Exception e) {
                    }
                }
            }
       
            hideNotification();
           
            Log.i("ServiceStartArguments", "Done with #" + msg.arg1);
            stopSelf(msg.arg1);
        }

    };
   
    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        Toast.makeText(this, R.string.service_created,
                Toast.LENGTH_SHORT).show();
       
        mInvokeIntent = new Intent(this, ServiceStartArgumentsController.class);

        HandlerThread thread = new HandlerThread("ServiceStartArguments",
                Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
       
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("ServiceStartArguments",
                "Starting #" + startId + ": " + intent.getExtras());
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.arg2 = flags;
        msg.obj = intent.getExtras();
        mServiceHandler.sendMessage(msg);
        Log.i("ServiceStartArguments", "Sending: " + msg);
       
        if (intent.getBooleanExtra("fail", false)) {

            if ((flags&START_FLAG_RETRY) == 0) {

                Process.killProcess(Process.myPid());
            }
        }
       
        return intent.getBooleanExtra("redeliver", false)
                ? START_REDELIVER_INTENT : START_NOT_STICKY;

    }

    @Override
    public void onDestroy() {
        mServiceLooper.quit();

        hideNotification();

        Toast.makeText(ServiceStartArguments.this, R.string.service_destroyed,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void showNotification(String text) {
        Notification notification = new Notification(R.drawable.stat_sample, text,
                System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, AlarmService.class), 0);

        notification.setLatestEventInfo(this, getText(R.string.service_start_arguments_label),
                       text, contentIntent);

        notification.flags |= Notification.FLAG_ONGOING_EVENT;
       
        mNM.notify(R.string.service_created, notification);
    }
   
    private void hideNotification() {
        mNM.cancel(R.string.service_created);

    }
}



[Manifest.xml]

<service android:name=".app.RemoteService" android:process=":remote">
            <intent-filter>
                <action android:name="com.example.android.apis.app.IRemoteService" />
                <action android:name="com.example.android.apis.app.ISecondary" />
             <action android:name="com.example.android.apis.app.REMOTE_SERVICE" />
            </intent-filter>
        </service>

'old > API_Demo' 카테고리의 다른 글

APP_VoiceRecognition  (0) 2010.03.25
APP_TextToSpeech  (0) 2010.03.25
APP_Service_RemoteServiceBinding  (0) 2010.03.25
APP_Service_RemoteServiceController  (0) 2010.03.25
APP_Service_LocalServiceController  (0) 2010.03.25
Posted by jazzlife
,

[RemoteServiceBinding.java]

public class RemoteServiceBinding extends Activity {

    IRemoteService mService = null;
    ISecondary mSecondaryService = null;

   
    Button mKillButton;
    TextView mCallbackText;

    private boolean mIsBound;

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

.
.
.
    }

     private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {

            mService = IRemoteService.Stub.asInterface(service);
            mKillButton.setEnabled(true);
            mCallbackText.setText("Attached.");

            try {
                mService.registerCallback(mCallback);
            } catch (RemoteException e) {
            }

            Toast.makeText(RemoteServiceBinding.this, R.string.remote_service_connected,
                    Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName className) {

            mService = null;
            mKillButton.setEnabled(false);
            mCallbackText.setText("Disconnected.");

            Toast.makeText(RemoteServiceBinding.this, R.string.remote_service_disconnected,
                    Toast.LENGTH_SHORT).show();
        }
    };

    private ServiceConnection mSecondaryConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className,
                IBinder service) {

            mSecondaryService = ISecondary.Stub.asInterface(service);
            mKillButton.setEnabled(true);
        }

        public void onServiceDisconnected(ComponentName className) {
            mSecondaryService = null;
            mKillButton.setEnabled(false);
        }
    };

    private OnClickListener mBindListener = new OnClickListener() {
        public void onClick(View v) {

            bindService(new Intent(IRemoteService.class.getName()),
                    mConnection, Context.BIND_AUTO_CREATE);
            bindService(new Intent(ISecondary.class.getName()),
                    mSecondaryConnection, Context.BIND_AUTO_CREATE);
            mIsBound = true;
            mCallbackText.setText("Binding.");
        }
    };

    private OnClickListener mUnbindListener = new OnClickListener() {
        public void onClick(View v) {
            if (mIsBound) {

                if (mService != null) {
                    try {
                        mService.unregisterCallback(mCallback);
                    } catch (RemoteException e) {

                    }
                }
               
                unbindService(mConnection);
                unbindService(mSecondaryConnection);
                mKillButton.setEnabled(false);
                mIsBound = false;
                mCallbackText.setText("Unbinding.");
            }
        }
    };

    private OnClickListener mKillListener = new OnClickListener() {
        public void onClick(View v) {

            if (mSecondaryService != null) {
                try {
                    int pid = mSecondaryService.getPid();

                    Process.killProcess(pid);
                    mCallbackText.setText("Killed service process.");
                } catch (RemoteException ex) {

                    Toast.makeText(RemoteServiceBinding.this,
                            R.string.remote_call_failed,
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    };
   
    private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {

        public void valueChanged(int value) {
            mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0));
        }
    };
   
    private static final int BUMP_MSG = 1;
   
    private Handler mHandler = new Handler() {
        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
                case BUMP_MSG:
                    mCallbackText.setText("Received from service: " + msg.arg1);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
       
    };
}



[RemoteService.java]

   final RemoteCallbackList<IRemoteServiceCallback> mCallbacks
            = new RemoteCallbackList<IRemoteServiceCallback>();
   
    int mValue = 0;
    NotificationManager mNM;

   
    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        showNotification();
       
        mHandler.sendEmptyMessage(REPORT_MSG);

    }

    @Override
    public void onDestroy() {
        mNM.cancel(R.string.remote_service_started);

        Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();
       
        mCallbacks.kill();
       
        mHandler.removeMessages(REPORT_MSG);

    }
   

    @Override
    public IBinder onBind(Intent intent) {
        if (IRemoteService.class.getName().equals(intent.getAction())) {
            return mBinder;
        }
        if (ISecondary.class.getName().equals(intent.getAction())) {
            return mSecondaryBinder;
        }
        return null;

    }

    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
        public void registerCallback(IRemoteServiceCallback cb) {
            if (cb != null) mCallbacks.register(cb);

        }
        public void unregisterCallback(IRemoteServiceCallback cb) {
            if (cb != null) mCallbacks.unregister(cb);

        }
    };

    private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() {
        public int getPid() {
            return Process.myPid();

        }
        public void basicTypes(int anInt, long aLong, boolean aBoolean,
                float aFloat, double aDouble, String aString) {

        }
    };

   
    private static final int REPORT_MSG = 1;
   
    private final Handler mHandler = new Handler() {

        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
               
                case REPORT_MSG: {
                    int value = ++mValue;

                    final int N = mCallbacks.beginBroadcast();
                    for (int i=0; i<N; i++) {
                        try {
                            mCallbacks.getBroadcastItem(i).valueChanged(value);
                        } catch (RemoteException e) {
                        }
                    }
                    mCallbacks.finishBroadcast();
                   
                    sendMessageDelayed(obtainMessage(REPORT_MSG), 1*1000);
                } break;
                default:
                    super.handleMessage(msg);
            }
        }
    };

    private void showNotification() {
        CharSequence text = getText(R.string.remote_service_started);

        Notification notification = new Notification(R.drawable.stat_sample, text,
                System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, LocalServiceController.class), 0);

        notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
                       text, contentIntent);

        mNM.notify(R.string.remote_service_started, notification);
    }
}



[Manifest.xml]

<service android:name=".app.RemoteService" android:process=":remote">
            <intent-filter>
                <action android:name="com.example.android.apis.app.IRemoteService" />
                <action android:name="com.example.android.apis.app.ISecondary" />
                <action android:name="com.example.android.apis.app.REMOTE_SERVICE" />
            </intent-filter>
        </service>


[IRemoteService.aidl]

package com.example.android.apis.app;
import com.example.android.apis.app.IRemoteServiceCallback;

interface IRemoteService {
    void registerCallback(IRemoteServiceCallback cb);
    void unregisterCallback(IRemoteServiceCallback cb);
}



[IRemoteServiceCallback.aidl]

package com.example.android.apis.app;

oneway interface IRemoteServiceCallback {
  
    void valueChanged(int value);
}


[ISecondary.aidl]

package com.example.android.apis.app;
interface ISecondary {
    int getPid();
     void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
}

'old > API_Demo' 카테고리의 다른 글

APP_TextToSpeech  (0) 2010.03.25
APP_Service_ServiceStartArgumentsController  (0) 2010.03.25
APP_Service_RemoteServiceController  (0) 2010.03.25
APP_Service_LocalServiceController  (0) 2010.03.25
APP_Service_LocalServiceBinding  (0) 2010.03.25
Posted by jazzlife
,

[RemoteServiceController.java]

  private OnClickListener mStartListener = new OnClickListener() {
        public void onClick(View v) {
            startService(new Intent(
                    "com.example.android.apis.app.REMOTE_SERVICE"));

        }
    };

    private OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v) {
            stopService(new Intent(
                    "com.example.android.apis.app.REMOTE_SERVICE"));

        }
    };
}


[RemoteService.java]

   final RemoteCallbackList<IRemoteServiceCallback> mCallbacks
            = new RemoteCallbackList<IRemoteServiceCallback>();
   
    int mValue = 0;
    NotificationManager mNM;

   
    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        showNotification();
       
        mHandler.sendEmptyMessage(REPORT_MSG);

    }

    @Override
    public void onDestroy() {
        mNM.cancel(R.string.remote_service_started);

        Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();
       
        mCallbacks.kill();
       
        mHandler.removeMessages(REPORT_MSG);

    }
   

    @Override
    public IBinder onBind(Intent intent) {
        if (IRemoteService.class.getName().equals(intent.getAction())) {
            return mBinder;
        }
        if (ISecondary.class.getName().equals(intent.getAction())) {
            return mSecondaryBinder;
        }
        return null;

    }

    private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
        public void registerCallback(IRemoteServiceCallback cb) {
            if (cb != null) mCallbacks.register(cb);

        }
        public void unregisterCallback(IRemoteServiceCallback cb) {
            if (cb != null) mCallbacks.unregister(cb);

        }
    };

    private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() {
        public int getPid() {
            return Process.myPid();

        }
        public void basicTypes(int anInt, long aLong, boolean aBoolean,
                float aFloat, double aDouble, String aString) {

        }
    };

   
    private static final int REPORT_MSG = 1;
   
    private final Handler mHandler = new Handler() {

        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
               
                case REPORT_MSG: {
                    int value = ++mValue;

                    final int N = mCallbacks.beginBroadcast();
                    for (int i=0; i<N; i++) {
                        try {
                            mCallbacks.getBroadcastItem(i).valueChanged(value);
                        } catch (RemoteException e) {
                        }
                    }
                    mCallbacks.finishBroadcast();
                   
                    sendMessageDelayed(obtainMessage(REPORT_MSG), 1*1000);
                } break;
                default:
                    super.handleMessage(msg);
            }
        }
    };

    private void showNotification() {
        CharSequence text = getText(R.string.remote_service_started);

        Notification notification = new Notification(R.drawable.stat_sample, text,
                System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, LocalServiceController.class), 0);

        notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
                       text, contentIntent);

        mNM.notify(R.string.remote_service_started, notification);
    }
}


[Manifest.xml]

<service android:name=".app.RemoteService" android:process=":remote">
            <intent-filter>
                <action android:name="com.example.android.apis.app.IRemoteService" />
                <action android:name="com.example.android.apis.app.ISecondary" />
                <action android:name="com.example.android.apis.app.REMOTE_SERVICE" />
            </intent-filter>
        </service>


[IRemoteService.aidl]

package com.example.android.apis.app;
import com.example.android.apis.app.IRemoteServiceCallback;

interface IRemoteService {
    void registerCallback(IRemoteServiceCallback cb);
    void unregisterCallback(IRemoteServiceCallback cb);
}



[IRemoteServiceCallback.aidl]

package com.example.android.apis.app;

oneway interface IRemoteServiceCallback {
  
    void valueChanged(int value);
}


[ISecondary.aidl]

package com.example.android.apis.app;
interface ISecondary {
    int getPid();
     void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
}




 

'old > API_Demo' 카테고리의 다른 글

APP_Service_ServiceStartArgumentsController  (0) 2010.03.25
APP_Service_RemoteServiceBinding  (0) 2010.03.25
APP_Service_LocalServiceController  (0) 2010.03.25
APP_Service_LocalServiceBinding  (0) 2010.03.25
APP_Service_ForegroundServiceController  (0) 2010.03.24
Posted by jazzlife
,

[LocalServiceController.java]

    private OnClickListener mStartListener = new OnClickListener() {
        public void onClick(View v)
        {

            startService(new Intent(LocalServiceController.this,
                    LocalService.class));

        }
    };

    private OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v)
        {

            stopService(new Intent(LocalServiceController.this,
                    LocalService.class));

        }
    };



[LocalService.java]

private NotificationManager mNM;

      public class LocalBinder extends Binder {
        LocalService getService() {
            return LocalService.this;
        }

    }
   
    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        showNotification();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
 mNM.cancel(R.string.local_service_started);

 Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private final IBinder mBinder = new LocalBinder();

    private void showNotification() {
        CharSequence text = getText(R.string.local_service_started);
        Notification notification = new Notification(R.drawable.stat_sample, text,
                System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, LocalServiceController.class), 0);

        notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                       text, contentIntent);

        mNM.notify(R.string.local_service_started, notification);
    }
}

'old > API_Demo' 카테고리의 다른 글

APP_Service_RemoteServiceBinding  (0) 2010.03.25
APP_Service_RemoteServiceController  (0) 2010.03.25
APP_Service_LocalServiceBinding  (0) 2010.03.25
APP_Service_ForegroundServiceController  (0) 2010.03.24
APP_Search  (0) 2010.03.24
Posted by jazzlife
,

[LocalServiceBinding.java]

    private boolean mIsBound;
    private LocalService mBoundService;

.
.
.
  private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {

            mBoundService = ((LocalService.LocalBinder)service).getService();
           
            Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,
                    Toast.LENGTH_SHORT).show();
        }

        public void onServiceDisconnected(ComponentName className) {

            mBoundService = null;
            Toast.makeText(LocalServiceBinding.this, R.string.local_service_disconnected,
                    Toast.LENGTH_SHORT).show();
        }
    };

    private OnClickListener mBindListener = new OnClickListener() {
        public void onClick(View v) {

            bindService(new Intent(LocalServiceBinding.this,
                    LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
            mIsBound = true;
        }
    };

    private OnClickListener mUnbindListener = new OnClickListener() {
        public void onClick(View v) {
            if (mIsBound) {
                unbindService(mConnection);
                mIsBound = false;
            }
        }
    };



[LocalService.java]

private NotificationManager mNM;

      public class LocalBinder extends Binder {
        LocalService getService() {
            return LocalService.this;
        }

    }
   
    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        showNotification();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
 mNM.cancel(R.string.local_service_started);

 Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private final IBinder mBinder = new LocalBinder();

    private void showNotification() {
        CharSequence text = getText(R.string.local_service_started);
        Notification notification = new Notification(R.drawable.stat_sample, text,
                System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, LocalServiceController.class), 0);

        notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                       text, contentIntent);

        mNM.notify(R.string.local_service_started, notification);
    }
}

'old > API_Demo' 카테고리의 다른 글

APP_Service_RemoteServiceController  (0) 2010.03.25
APP_Service_LocalServiceController  (0) 2010.03.25
APP_Service_ForegroundServiceController  (0) 2010.03.24
APP_Search  (0) 2010.03.24
APP_Preferences_PreferencesFromCode  (0) 2010.03.24
Posted by jazzlife
,

[ForegroundServiceController.java]

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

        setContentView(R.layout.foreground_service_controller);

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.start_foreground);
        button.setOnClickListener(mForegroundListener);
        button = (Button)findViewById(R.id.start_background);
        button.setOnClickListener(mBackgroundListener);
        button = (Button)findViewById(R.id.stop);
        button.setOnClickListener(mStopListener);
    }

    private OnClickListener mForegroundListener = new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(ForegroundService.ACTION_FOREGROUND);
            intent.setClass(ForegroundServiceController.this, ForegroundService.class);
            startService(intent);

        }
    };

    private OnClickListener mBackgroundListener = new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(ForegroundService.ACTION_BACKGROUND);
            intent.setClass(ForegroundServiceController.this, ForegroundService.class);
            startService(intent);
        }
    };

    private OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v) {
            stopService(new Intent(ForegroundServiceController.this,
                    ForegroundService.class));

        }
    };
}



[ForegroundService.java]

    static final String ACTION_FOREGROUND = "com.example.android.apis.FOREGROUND";
    static final String ACTION_BACKGROUND = "com.example.android.apis.BACKGROUND";
   
    private static final Class[] mStartForegroundSignature = new Class[] {
        int.class, Notification.class};
    private static final Class[] mStopForegroundSignature = new Class[] {
        boolean.class};
   
    private NotificationManager mNM;
    private Method mStartForeground;
    private Method mStopForeground;
    private Object[] mStartForegroundArgs = new Object[2];
    private Object[] mStopForegroundArgs = new Object[1];
   
    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        try {
            mStartForeground = getClass().getMethod("startForeground",
                    mStartForegroundSignature);
            mStopForeground = getClass().getMethod("stopForeground",
                    mStopForegroundSignature);
        } catch (NoSuchMethodException e) {
            // Running on an older platform.
            mStartForeground = mStopForeground = null;
        }
    }

    // This is the old onStart method that will be called on the pre-2.0
    // platform.  On 2.0 or later we override onStartCommand() so this
    // method will not be called.
    @Override
    public void onStart(Intent intent, int startId) {
        handleCommand(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handleCommand(intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    void handleCommand(Intent intent) {
        if (ACTION_FOREGROUND.equals(intent.getAction())) {
   // In this sample, we'll use the same text for the ticker and the expanded notification
            CharSequence text = getText(R.string.foreground_service_started);

            // Set the icon, scrolling text and timestamp
            Notification notification = new Notification(R.drawable.stat_sample, text,
                    System.currentTimeMillis());

            // The PendingIntent to launch our activity if the user selects this notification
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                    new Intent(this, ForegroundServiceController.class), 0);

            // Set the info for the views that show in the notification panel.
            notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                           text, contentIntent);
           
            startForegroundCompat(R.string.foreground_service_started, notification);
           
        } else if (ACTION_BACKGROUND.equals(intent.getAction())) {
            stopForegroundCompat(R.string.foreground_service_started);
        }
    }
   
    /**
     * This is a wrapper around the new startForeground method, using the older
     * APIs if it is not available.
     */

    void startForegroundCompat(int id, Notification notification) {
        // If we have the new startForeground API, then use it.
        if (mStartForeground != null) {
            mStartForegroundArgs[0] = Integer.valueOf(id);
            mStartForegroundArgs[1] = notification;
            try {
                mStartForeground.invoke(this, mStartForegroundArgs);
            } catch (InvocationTargetException e) {
                // Should not happen.
                Log.w("ApiDemos", "Unable to invoke startForeground", e);
            } catch (IllegalAccessException e) {
                // Should not happen.
                Log.w("ApiDemos", "Unable to invoke startForeground", e);
            }
            return;
        }
       
        // Fall back on the old API.
        setForeground(true);
        mNM.notify(id, notification);
    }
   
    /**
     * This is a wrapper around the new stopForeground method, using the older
     * APIs if it is not available.
     */

    void stopForegroundCompat(int id) {
        // If we have the new stopForeground API, then use it.
        if (mStopForeground != null) {
            mStopForegroundArgs[0] = Boolean.TRUE;
            try {
                mStopForeground.invoke(this, mStopForegroundArgs);
            } catch (InvocationTargetException e) {
                // Should not happen.
                Log.w("ApiDemos", "Unable to invoke stopForeground", e);
            } catch (IllegalAccessException e) {
                // Should not happen.
                Log.w("ApiDemos", "Unable to invoke stopForeground", e);
            }
            return;
        }
       
        // Fall back on the old API.  Note to cancel BEFORE changing the
        // foreground state, since we could be killed at that point.

        mNM.cancel(id);
        setForeground(false);
    }
   
    @Override
    public void onDestroy() {
        // Make sure our notification is gone.
        stopForegroundCompat(R.string.foreground_service_started);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

'old > API_Demo' 카테고리의 다른 글

APP_Service_LocalServiceController  (0) 2010.03.25
APP_Service_LocalServiceBinding  (0) 2010.03.25
APP_Search  (0) 2010.03.24
APP_Preferences_PreferencesFromCode  (0) 2010.03.24
APP_Preferences_DefaultValues  (0) 2010.03.24
Posted by jazzlife
,

APP_Search

old/API_Demo 2010. 3. 24. 15:05

[SearchInvoke.java]


    Button mStartSearch;
    Spinner mMenuMode;
    EditText mQueryPrefill;
    EditText mQueryAppData;

   
    final static int MENUMODE_SEARCH_KEY = 0;
    final static int MENUMODE_MENU_ITEM = 1;
    final static int MENUMODE_TYPE_TO_SEARCH = 2;
    final static int MENUMODE_DISABLED = 3;

   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        // Inflate our UI from its XML layout description.
        setContentView(R.layout.search_invoke);
       
        // Get display items for later interaction
        mStartSearch = (Button) findViewById(R.id.btn_start_search);
        mMenuMode = (Spinner) findViewById(R.id.spinner_menu_mode);
        mQueryPrefill = (EditText) findViewById(R.id.txt_query_prefill);
        mQueryAppData = (EditText) findViewById(R.id.txt_query_appdata);
       
        // Populate items
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                            this, R.array.search_menuModes, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mMenuMode.setAdapter(adapter);
       
    // Create listener for the menu mode dropdown.  We use this to demonstrate control
    // of the default keys handler in every Activity.  More typically, you will simply set
    // the default key mode in your activity's onCreate() handler.

        mMenuMode.setOnItemSelectedListener(
            new OnItemSelectedListener() {
                public void onItemSelected(
                        AdapterView<?> parent, View view, int position, long id) {
                    if (position == MENUMODE_TYPE_TO_SEARCH) {
                        setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
                    } else {
                        setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
                    }
                }

                public void onNothingSelected(AdapterView<?> parent) {
                    setDefaultKeyMode(DEFAULT_KEYS_DISABLE);
                }
            });
       
        // Attach actions to buttons
        mStartSearch.setOnClickListener(
            new OnClickListener() {
                public void onClick(View v) {
                    onSearchRequested();
                }
            });
    }
   
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        MenuItem item;
       
            // first, get rid of our menus (if any)
        menu.removeItem(0);
        menu.removeItem(1);
       
            // next, add back item(s) based on current menu mode
        switch (mMenuMode.getSelectedItemPosition())
        {
        case MENUMODE_SEARCH_KEY:
            item = menu.add( 0, 0, 0, "(Search Key)");
            break;
           
        case MENUMODE_MENU_ITEM:
            item = menu.add( 0, 0, 0, "Search");
            item.setAlphabeticShortcut(SearchManager.MENU_KEY);
            break;
           
        case MENUMODE_TYPE_TO_SEARCH:
            item = menu.add( 0, 0, 0, "(Type-To-Search)");
            break;
           
        case MENUMODE_DISABLED:
            item = menu.add( 0, 0, 0, "(Disabled)");
            break;
        }
       
        item = menu.add(0, 1, 0, "Clear History");
        return true;
    }
   
    /** Handle the menu item selections */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 0:
            switch (mMenuMode.getSelectedItemPosition()) {
            case MENUMODE_SEARCH_KEY:
                new AlertDialog.Builder(this)
                    .setMessage("To invoke search, dismiss this dialog and press the search key" +
                                " (F5 on the simulator).")
                    .setPositiveButton("OK", null)
                    .show();
                break;
               
            case MENUMODE_MENU_ITEM:
                onSearchRequested();
                break;
               
            case MENUMODE_TYPE_TO_SEARCH:
                new AlertDialog.Builder(this)
                    .setMessage("To invoke search, dismiss this dialog and start typing.")
                    .setPositiveButton("OK", null)
                    .show();
                break;
               
            case MENUMODE_DISABLED:
                new AlertDialog.Builder(this)
                    .setMessage("You have disabled search.")
                    .setPositiveButton("OK", null)
                    .show();
                break;
            }
            break;
        case 1:
            clearSearchHistory();
            break;
        }
   
         return super.onOptionsItemSelected(item);
    }
   
    @Override
    public boolean onSearchRequested() {
        // If your application absolutely must disable search, do it here.
        if (mMenuMode.getSelectedItemPosition() == MENUMODE_DISABLED) {
            return false;
        }
       
        final String queryPrefill = mQueryPrefill.getText().toString();

        Bundle appDataBundle = null;
        final String queryAppDataString = mQueryAppData.getText().toString();
        if (queryAppDataString != null) {
            appDataBundle = new Bundle();
            appDataBundle.putString("demo_key", queryAppDataString);
        }
       
        // Now call the Activity member function that invokes the Search Manager UI.
        startSearch(queryPrefill, false, appDataBundle, false);
       
        // Returning true indicates that we did launch the search, instead of blocking it.
        return true;
    }
   
    private void clearSearchHistory() {
        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
                SearchSuggestionSampleProvider.AUTHORITY, SearchSuggestionSampleProvider.MODE);
        suggestions.clearHistory();
    }
   
}



[SearchQueryResoults.java]

        // UI elements
    TextView mQueryText;
    TextView mAppDataText;
    TextView mDeliveredByText;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        // Inflate our UI from its XML layout description.
        setContentView(R.layout.search_query_results);
       
        // Get active display items for later updates
        mQueryText = (TextView) findViewById(R.id.txt_query);
        mAppDataText = (TextView) findViewById(R.id.txt_appdata);
        mDeliveredByText = (TextView) findViewById(R.id.txt_deliveredby);
       
        // get and process search query here
        final Intent queryIntent = getIntent();
        final String queryAction = queryIntent.getAction();
        if (Intent.ACTION_SEARCH.equals(queryAction)) {
            doSearchQuery(queryIntent, "onCreate()");
        }
        else {
            mDeliveredByText.setText("onCreate(), but no ACTION_SEARCH intent");
        }
    }
   
    @Override
    public void onNewIntent(final Intent newIntent) {
        super.onNewIntent(newIntent);
       
        // get and process search query here
        final Intent queryIntent = getIntent();
        final String queryAction = queryIntent.getAction();
        if (Intent.ACTION_SEARCH.equals(queryAction)) {
            doSearchQuery(queryIntent, "onNewIntent()");
        }
        else {
            mDeliveredByText.setText("onNewIntent(), but no ACTION_SEARCH intent");
        }
    }
   
    private void doSearchQuery(final Intent queryIntent, final String entryPoint) {
       
        // The search query is provided as an "extra" string in the query intent
        final String queryString = queryIntent.getStringExtra(SearchManager.QUERY);
        mQueryText.setText(queryString);
       
        // Record the query string in the recent queries suggestions provider.
        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
                SearchSuggestionSampleProvider.AUTHORITY, SearchSuggestionSampleProvider.MODE);
        suggestions.saveRecentQuery(queryString, null);
       
        // If your application provides context data for its searches,
        // you will receive it as an "extra" bundle in the query intent.
        // The bundle can contain any number of elements, using any number of keys;
        // For this Api Demo we're just using a single string, stored using "demo key".
        final Bundle appData = queryIntent.getBundleExtra(SearchManager.APP_DATA);
        if (appData == null) {
            mAppDataText.setText("<no app data bundle>");
        }
        if (appData != null) {
            String testStr = appData.getString("demo_key");
            mAppDataText.setText((testStr == null) ? "<no app data>" : testStr);
        }
       
        // Report the method by which we were called.
        mDeliveredByText.setText(entryPoint);
    }
}



[arrays.xml]

<resources>
    <string-array name="search_menuModes">
        <item>Search Key</item>
        <item>Menu Item</item>
        <item>Type-To-Search</item>
        <item>Disabled</item>
    </string-array>
</resources>


'old > API_Demo' 카테고리의 다른 글

APP_Service_LocalServiceBinding  (0) 2010.03.25
APP_Service_ForegroundServiceController  (0) 2010.03.24
APP_Preferences_PreferencesFromCode  (0) 2010.03.24
APP_Preferences_DefaultValues  (0) 2010.03.24
APP_PreferenceDependencies  (0) 2010.03.24
Posted by jazzlife
,

[PreferencesFromCode.java]

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

    private PreferenceScreen createPreferenceHierarchy() {
        PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
       
        // Inline preferences
        PreferenceCategory inlinePrefCat = new PreferenceCategory(this);
        inlinePrefCat.setTitle(R.string.inline_preferences);
        root.addPreference(inlinePrefCat);
       
        // Toggle preference
        CheckBoxPreference togglePref = new CheckBoxPreference(this);
        togglePref.setKey("toggle_preference");
        togglePref.setTitle(R.string.title_toggle_preference);
        togglePref.setSummary(R.string.summary_toggle_preference);
        inlinePrefCat.addPreference(togglePref);
               
        // Dialog based preferences
        PreferenceCategory dialogBasedPrefCat = new PreferenceCategory(this);
        dialogBasedPrefCat.setTitle(R.string.dialog_based_preferences);
        root.addPreference(dialogBasedPrefCat);

        // Edit text preference
        EditTextPreference editTextPref = new EditTextPreference(this);
        editTextPref.setDialogTitle(R.string.dialog_title_edittext_preference);
        editTextPref.setKey("edittext_preference");
        editTextPref.setTitle(R.string.title_edittext_preference);
        editTextPref.setSummary(R.string.summary_edittext_preference);
        dialogBasedPrefCat.addPreference(editTextPref);
       
        // List preference
        ListPreference listPref = new ListPreference(this);
        listPref.setEntries(R.array.entries_list_preference);
        listPref.setEntryValues(R.array.entryvalues_list_preference);
        listPref.setDialogTitle(R.string.dialog_title_list_preference);
        listPref.setKey("list_preference");
        listPref.setTitle(R.string.title_list_preference);
        listPref.setSummary(R.string.summary_list_preference);
        dialogBasedPrefCat.addPreference(listPref);
       
        // Launch preferences
        PreferenceCategory launchPrefCat = new PreferenceCategory(this);
        launchPrefCat.setTitle(R.string.launch_preferences);
        root.addPreference(launchPrefCat);

        // Screen preference
        PreferenceScreen screenPref = getPreferenceManager().createPreferenceScreen(this);
        screenPref.setKey("screen_preference");
        screenPref.setTitle(R.string.title_screen_preference);
        screenPref.setSummary(R.string.summary_screen_preference);
        launchPrefCat.addPreference(screenPref);
               
        // Example of next screen toggle preference
        CheckBoxPreference nextScreenCheckBoxPref = new CheckBoxPreference(this);
        nextScreenCheckBoxPref.setKey("next_screen_toggle_preference");
        nextScreenCheckBoxPref.setTitle(R.string.title_next_screen_toggle_preference);
        nextScreenCheckBoxPref.setSummary(R.string.summary_next_screen_toggle_preference);
        screenPref.addPreference(nextScreenCheckBoxPref);
       
        // Intent preference
        PreferenceScreen intentPref = getPreferenceManager().createPreferenceScreen(this);
        intentPref.setIntent(new Intent().setAction(Intent.ACTION_VIEW)
                .setData(Uri.parse("http://www.android.com")));
        intentPref.setTitle(R.string.title_intent_preference);
        intentPref.setSummary(R.string.summary_intent_preference);
        launchPrefCat.addPreference(intentPref);
       
        // Preference attributes
        PreferenceCategory prefAttrsCat = new PreferenceCategory(this);
        prefAttrsCat.setTitle(R.string.preference_attributes);
        root.addPreference(prefAttrsCat);
       
        // Visual parent toggle preference
        CheckBoxPreference parentCheckBoxPref = new CheckBoxPreference(this);
        parentCheckBoxPref.setTitle(R.string.title_parent_preference);
        parentCheckBoxPref.setSummary(R.string.summary_parent_preference);
        prefAttrsCat.addPreference(parentCheckBoxPref);
       
        // Visual child toggle preference
        // See res/values/attrs.xml for the <declare-styleable> that defines
        // TogglePrefAttrs.

        TypedArray a = obtainStyledAttributes(R.styleable.TogglePrefAttrs);
        CheckBoxPreference childCheckBoxPref = new CheckBoxPreference(this);
        childCheckBoxPref.setTitle(R.string.title_child_preference);
        childCheckBoxPref.setSummary(R.string.summary_child_preference);
        childCheckBoxPref.setLayoutResource(
                a.getResourceId(R.styleable.TogglePrefAttrs_android_preferenceLayoutChild,
                        0));
        prefAttrsCat.addPreference(childCheckBoxPref);
        a.recycle();
       
        return root;
    }
}



[attrs.xml]

<resources>
    <declare-styleable name="TogglePrefAttrs">
        <attr name="android:preferenceLayoutChild" />
    </declare-styleable>
</resources>

'old > API_Demo' 카테고리의 다른 글

APP_Service_ForegroundServiceController  (0) 2010.03.24
APP_Search  (0) 2010.03.24
APP_Preferences_DefaultValues  (0) 2010.03.24
APP_PreferenceDependencies  (0) 2010.03.24
APP_Preferences_LaunchingPreferences  (0) 2010.03.23
Posted by jazzlife
,
[DefaultValues.java]

addPreferencesFromResource(R.xml.default_values);




[default_values.xml]

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

    <CheckBoxPreference
            android:key="default_toggle"
            android:defaultValue="true"
            android:title="@string/title_checkbox_preference"
            android:summary="@string/summary_checkbox_preference" />

    <EditTextPreference
            android:key="default_edittext"
            android:defaultValue="@string/default_value_edittext_preference"
            android:title="@string/title_edittext_preference"
            android:summary="@string/summary_edittext_preference"
            android:dialogTitle="@string/dialog_title_edittext_preference" />
           
    <ListPreference
            android:key="default_list"
          android:defaultValue="@string/default_value_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" />

</PreferenceScreen>



[arrays.xml]

<resources>
    <string-array name="entries_list_preference">
        <item>Alpha Option 01</item>
        <item>Beta Option 02</item>
        <item>Charlie Option 03</item> 
    </string-array>

    <string-array name="entryvalues_list_preference">
        <item>alpha</item>
        <item>beta</item>
        <item>charlie</item> 
    </string-array>
</resources>

 

'old > API_Demo' 카테고리의 다른 글

APP_Search  (0) 2010.03.24
APP_Preferences_PreferencesFromCode  (0) 2010.03.24
APP_PreferenceDependencies  (0) 2010.03.24
APP_Preferences_LaunchingPreferences  (0) 2010.03.23
APP_Preferences_PreferencesFromXML  (0) 2010.03.23
Posted by jazzlife
,

[PreferenceDependencies.java]

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        addPreferencesFromResource(R.xml.preference_dependencies);
    }

}



[preference_depencencies.xml]

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

    <PreferenceCategory
            android:title="@string/example_preference_dependency">
           
        <CheckBoxPreference
                android:key="wifi"
                android:title="@string/title_wifi" />
           
        <EditTextPreference
                android:layout="?android:attr/preferenceLayoutChild"
                android:title="@string/title_wifi_settings"
                android:dependency="wifi" />
           
    </PreferenceCategory>
</PreferenceScreen>


'old > API_Demo' 카테고리의 다른 글

APP_Preferences_PreferencesFromCode  (0) 2010.03.24
APP_Preferences_DefaultValues  (0) 2010.03.24
APP_Preferences_LaunchingPreferences  (0) 2010.03.23
APP_Preferences_PreferencesFromXML  (0) 2010.03.23
APP_Notification_StatusBar  (0) 2010.03.23
Posted by jazzlife
,

[LaunchingPreferences.java]

    private static final int REQUEST_CODE_PREFERENCES = 1;
    private TextView mCounterText;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false);
       
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);
       
        Button launchPreferences = new Button(this);
        launchPreferences.setText(getString(R.string.launch_preference_activity));
        launchPreferences.setOnClickListener(this);
        layout.addView(launchPreferences, new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
       
        mCounterText = new TextView(this);
        layout.addView(mCounterText, new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
       
        updateCounterText();
    }

    public void onClick(View v) {
       
        Intent launchPreferencesIntent = new Intent().setClass(this, AdvancedPreferences.class);
       
        startActivityForResult(launchPreferencesIntent, REQUEST_CODE_PREFERENCES);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       
        if (requestCode == REQUEST_CODE_PREFERENCES) {
            updateCounterText();
        }
    }

    private void updateCounterText() {
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        final int counter = sharedPref.getInt(AdvancedPreferences.KEY_MY_PREFERENCE, 0);
        mCounterText.setText(getString(R.string.counter_value_is) + " " + counter);
    }
}



[AdvancedPreferences.class]


   public static final String KEY_MY_PREFERENCE = "my_preference";
    public static final String KEY_ADVANCED_CHECKBOX_PREFERENCE = "advanced_checkbox_preference";

    private CheckBoxPreference mCheckBoxPreference;
    private Handler mHandler = new Handler();

   
    private Runnable mForceCheckBoxRunnable = new Runnable() {
        public void run() {
            if (mCheckBoxPreference != null) {
                mCheckBoxPreference.setChecked(!mCheckBoxPreference.isChecked());
            }
           
              mHandler.postDelayed(this, 1000);
        }
    };
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.advanced_preferences);
       
        mCheckBoxPreference = (CheckBoxPreference)getPreferenceScreen().findPreference(KEY_ADVANCED_CHECKBOX_PREFERENCE);
    }

    @Override
    protected void onResume() {
        super.onResume();

        mForceCheckBoxRunnable.run();
       
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
       
        mHandler.removeCallbacks(mForceCheckBoxRunnable);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals(KEY_MY_PREFERENCE)) {
            Toast.makeText(this, "Thanks! You increased my count to "
                    + sharedPreferences.getInt(key, 0), Toast.LENGTH_SHORT).show();
        }
    }
   
}


[MyPreference.java]

   private int mClickCounter;

    public MyPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
       
        setWidgetLayoutResource(R.layout.preference_widget_mypreference);       
    }

    @Override
    protected void onBindView (View view) {
        super.onBindView(view);
       
        final TextView myTextView = (TextView) view.findViewById(R.id.mypreference_widget);
        if (myTextView != null) {
            myTextView.setText(String.valueOf(mClickCounter));
        }
    }

    @Override
    protected void onClick() {
        int newValue = mClickCounter + 1;
        if (!callChangeListener(newValue)) {
            return;
        }
       
        mClickCounter = newValue;
       
        persistInt(mClickCounter);
       
        notifyChanged();
    }

    @Override
    protected Object onGetDefaultValue(TypedArray a, int index) {
        return a.getInteger(index, 0);
    }

    @Override
    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
        if (restoreValue) {
            mClickCounter = getPersistedInt(mClickCounter);
        } else {
            int value = (Integer) defaultValue;
            mClickCounter = value;
            persistInt(value);
        }
    }

    @Override
    protected Parcelable onSaveInstanceState() {
       
        final Parcelable superState = super.onSaveInstanceState();
        if (isPersistent()) {
            return superState;
        }

        final SavedState myState = new SavedState(superState);
        myState.clickCounter = mClickCounter;
        return myState;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (!state.getClass().equals(SavedState.class)) {
            super.onRestoreInstanceState(state);
            return;
        }

        SavedState myState = (SavedState) state;
        super.onRestoreInstanceState(myState.getSuperState());
        mClickCounter = myState.clickCounter;
        notifyChanged();
    }
   
    private static class SavedState extends BaseSavedState {
        int clickCounter;
       
        public SavedState(Parcel source) {
            super(source);
           
            clickCounter = source.readInt();
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
           
            dest.writeInt(clickCounter);
        }

        public SavedState(Parcelable superState) {
            super(superState);
        }

        public static final Parcelable.Creator<SavedState> CREATOR =
                new Parcelable.Creator<SavedState>() {
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];

            }
        };
    }
   
}



[advances_preferences.xml]

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

    <com.example.android.apis.app.MyPreference
            android:key="my_preference"
            android:title="@string/title_my_preference"
            android:summary="@string/summary_my_preference"
            android:defaultValue="100" />

    <CheckBoxPreference
            android:key="advanced_checkbox_preference"
            android:title="@string/title_advanced_toggle_preference"
            android:summaryOn="@string/summary_on_advanced_toggle_preference"
            android:summaryOff="@string/summary_off_advanced_toggle_preference" />

</PreferenceScreen>

'old > API_Demo' 카테고리의 다른 글

APP_Preferences_DefaultValues  (0) 2010.03.24
APP_PreferenceDependencies  (0) 2010.03.24
APP_Preferences_PreferencesFromXML  (0) 2010.03.23
APP_Notification_StatusBar  (0) 2010.03.23
APP_Notification_NotifyWithText  (0) 2010.03.23
Posted by jazzlife
,

[PreferencesFromXML.java]

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

        addPreferencesFromResource(R.xml.preferences);
    }
}



[preferences.xml]

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

    <PreferenceCategory
            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" >

        <PreferenceScreen
                android:key="screen_preference"
                android:title="@string/title_screen_preference"
                android:summary="@string/summary_screen_preference">
                     
            <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">

            <intent android:action="android.intent.action.VIEW"
                    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" />

        <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>




[arrays.xml]

<Resources>
    <string-array name="entries_list_preference">
        <item>Alpha Option 01</item>
        <item>Beta Option 02</item>
        <item>Charlie Option 03</item> 
    </string-array>
</Resources>




'old > API_Demo' 카테고리의 다른 글

APP_PreferenceDependencies  (0) 2010.03.24
APP_Preferences_LaunchingPreferences  (0) 2010.03.23
APP_Notification_StatusBar  (0) 2010.03.23
APP_Notification_NotifyWithText  (0) 2010.03.23
APP_Notification_NotifyingServiceController  (0) 2010.03.23
Posted by jazzlife
,

[StatusBar.java]

   private NotificationManager mNotificationManager;
   private static int MOOD_NOTIFICATIONS = R.layout.status_bar_notifications;

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

        setContentView(R.layout.status_bar_notifications);

        Button button;

        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        button = (Button) findViewById(R.id.happy);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
    setMood(R.drawable.stat_happy, R.string.status_bar_notifications_happy_message,
                        false);
            }
        });

        button = (Button) findViewById(R.id.neutral);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
     setMood(R.drawable.stat_neutral, R.string.status_bar_notifications_ok_message,
                        false);
            }
        });

        button = (Button) findViewById(R.id.sad);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
       setMood(R.drawable.stat_sad, R.string.status_bar_notifications_sad_message, false);
            }
        });

        button = (Button) findViewById(R.id.happyMarquee);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
      setMood(R.drawable.stat_happy, R.string.status_bar_notifications_happy_message,
                        true);
            }
        });

        button = (Button) findViewById(R.id.neutralMarquee);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
      setMood(R.drawable.stat_neutral, R.string.status_bar_notifications_ok_message, true);
            }
        });

        button = (Button) findViewById(R.id.sadMarquee);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
      setMood(R.drawable.stat_sad, R.string.status_bar_notifications_sad_message, true);
            }
        });

        button = (Button) findViewById(R.id.happyViews);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
     setMoodView(R.drawable.stat_happy, R.string.status_bar_notifications_happy_message);
            }
        });

        button = (Button) findViewById(R.id.neutralViews);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
    setMoodView(R.drawable.stat_neutral, R.string.status_bar_notifications_ok_message);
            }
        });

        button = (Button) findViewById(R.id.sadViews);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
    setMoodView(R.drawable.stat_sad, R.string.status_bar_notifications_sad_message);
            }
        });
       
        button = (Button) findViewById(R.id.defaultSound);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setDefault(Notification.DEFAULT_SOUND);
            }
        });
       
        button = (Button) findViewById(R.id.defaultVibrate);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setDefault(Notification.DEFAULT_VIBRATE);
            }
        });
       
        button = (Button) findViewById(R.id.defaultAll);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setDefault(Notification.DEFAULT_ALL);
            }
        });
       
        button = (Button) findViewById(R.id.clear);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                mNotificationManager.cancel(R.layout.status_bar_notifications);
            }
        });
    }

    private PendingIntent makeMoodIntent(int moodId) {
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, NotificationDisplay.class)
                        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        .putExtra("moodimg", moodId),
                PendingIntent.FLAG_UPDATE_CURRENT);
        return contentIntent;
    }
   
    private void setMood(int moodId, int textId, boolean showTicker) {
         CharSequence text = getText(textId);

         String tickerText = showTicker ? getString(textId) : null;

        Notification notification = new Notification(moodId, tickerText,
                System.currentTimeMillis());

 notification.setLatestEventInfo(this, getText(R.string.status_bar_notifications_mood_title),
                       text, makeMoodIntent(moodId));

        mNotificationManager.notify(R.layout.status_bar_notifications, notification);
    }

    private void setMoodView(int moodId, int textId) {
        Notification notif = new Notification();

        notif.contentIntent = makeMoodIntent(moodId);

        CharSequence text = getText(textId);
        notif.tickerText = text;

        notif.icon = moodId;

        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.status_bar_balloon);
        contentView.setTextViewText(R.id.text, text);
        contentView.setImageViewResource(R.id.icon, moodId);
        notif.contentView = contentView;

        mNotificationManager.notify(R.layout.status_bar_notifications, notif);
    }
   
    private void setDefault(int defaults) {
       
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, StatusBarNotifications.class), 0);

        CharSequence text = getText(R.string.status_bar_notifications_happy_message);

        final Notification notification = new Notification(
                R.drawable.stat_happy, text, System.currentTimeMillis());

        notification.setLatestEventInfo(
                this,  getText(R.string.status_bar_notifications_mood_title),
                text, contentIntent);
        notification.defaults = defaults;
       
        mNotificationManager.notify(
                   R.layout.status_bar_notifications, notification);              
    }   
}



[Manifest.xml]

        <activity android:name=".app.StatusBarNotifications"
                android:label="App/Notification/Status Bar"
                android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.SAMPLE_CODE" />
            </intent-filter>
        </activity>

'old > API_Demo' 카테고리의 다른 글

APP_Preferences_LaunchingPreferences  (0) 2010.03.23
APP_Preferences_PreferencesFromXML  (0) 2010.03.23
APP_Notification_NotifyWithText  (0) 2010.03.23
APP_Notification_NotifyingServiceController  (0) 2010.03.23
APP_Notification_IncomingMessageView  (0) 2010.03.23
Posted by jazzlife
,

[NotifyWithText.java]

 button = (Button) findViewById(R.id.short_notify);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(NotifyWithText.this, R.string.short_notification_text,
                    Toast.LENGTH_SHORT).show();
            }
        });

        button = (Button) findViewById(R.id.long_notify);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(NotifyWithText.this, R.string.long_notification_text,
                    Toast.LENGTH_LONG).show();
            }
        });

'old > API_Demo' 카테고리의 다른 글

APP_Preferences_PreferencesFromXML  (0) 2010.03.23
APP_Notification_StatusBar  (0) 2010.03.23
APP_Notification_NotifyingServiceController  (0) 2010.03.23
APP_Notification_IncomingMessageView  (0) 2010.03.23
APP_Menu_InflateFromXML  (0) 2010.03.23
Posted by jazzlife
,

[NotifyingServiceController.java]

    private static int MOOD_NOTIFICATIONS = R.layout.status_bar_notifications;
    private ConditionVariable mCondition;

 
    @Override
    public void onCreate() {
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Thread notifyingThread = new Thread(null, mTask, "NotifyingService");
        mCondition = new ConditionVariable(false);
        notifyingThread.start();
    }

    @Override
    public void onDestroy() {
        mNM.cancel(MOOD_NOTIFICATIONS);
        mCondition.open();
    }

    private Runnable mTask = new Runnable() {
        public void run() {
            for (int i = 0; i < 4; ++i) {
                showNotification(R.drawable.stat_happy,
                        R.string.status_bar_notifications_happy_message);
                if (mCondition.block(5 * 1000))
                    break;
                showNotification(R.drawable.stat_neutral,
                        R.string.status_bar_notifications_ok_message);
                if (mCondition.block(5 * 1000))
                    break;
                showNotification(R.drawable.stat_sad,
                        R.string.status_bar_notifications_sad_message);
                if (mCondition.block(5 * 1000))
                    break;
            }
            NotifyingService.this.stopSelf();
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

   
    private void showNotification(int moodId, int textId) {
        CharSequence text = getText(textId);
        Notification notification = new Notification(moodId, null, System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, NotifyingController.class), 0);

        notification.setLatestEventInfo(this, getText(R.string.status_bar_notifications_mood_title),
                       text, contentIntent);

        mNM.notify(MOOD_NOTIFICATIONS, notification);
    }

    private final IBinder mBinder = new Binder() {
        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply,
                int flags) throws RemoteException {
            return super.onTransact(code, data, reply, flags);
        }
    };

    private NotificationManager mNM;
}



[Manifest.xml]

        <service android:name=".app.NotifyingService" />

        <activity android:name=".app.NotifyingController" android:label="App/Notification/Notifying Service Controller">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.SAMPLE_CODE" />
            </intent-filter>
        </activity>

'old > API_Demo' 카테고리의 다른 글

APP_Notification_StatusBar  (0) 2010.03.23
APP_Notification_NotifyWithText  (0) 2010.03.23
APP_Notification_IncomingMessageView  (0) 2010.03.23
APP_Menu_InflateFromXML  (0) 2010.03.23
APP_LauncherShortcuts  (0) 2010.03.23
Posted by jazzlife
,

  protected void showToast() {
        View view = inflateView(R.layout.incoming_message_panel);

        TextView tv = (TextView)view.findViewById(R.id.message);
        tv.setText("khtx. meet u for dinner. cul8r");

        Toast toast = new Toast(this);
        toast.setView(view);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.show();

    }

    private View inflateView(int resource) {
        LayoutInflater vi = (LayoutInflater)getSystemService           
                                    (Context.LAYOUT_INFLATER_SERVICE);
        return vi.inflate(resource, null);
    }

    protected void showNotification() {
        NotificationManager nm = (NotificationManager)getSystemService
                                                           (NOTIFICATION_SERVICE);

        CharSequence from = "Joe";
        CharSequence message = "kthx. meet u for dinner. cul8r";

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, IncomingMessageView.class), 0);

        String tickerText = getString(R.string.imcoming_message_ticker_text, message);

        Notification notif = new Notification(R.drawable.stat_sample, tickerText,
                System.currentTimeMillis());

        notif.setLatestEventInfo(this, from, message, contentIntent);

        notif.vibrate = new long[] { 100, 250, 100, 500};

        nm.notify(R.string.imcoming_message_ticker_text, notif);
    }
}

'old > API_Demo' 카테고리의 다른 글

APP_Notification_NotifyWithText  (0) 2010.03.23
APP_Notification_NotifyingServiceController  (0) 2010.03.23
APP_Menu_InflateFromXML  (0) 2010.03.23
APP_LauncherShortcuts  (0) 2010.03.23
APP_Intents  (0) 2010.03.23
Posted by jazzlife
,

[InflateFromXML.java]

   private static final int sMenuExampleResources[] = {
        R.menu.title_only, R.menu.title_icon, R.menu.submenu, R.menu.groups,
        R.menu.checkable, R.menu.shortcuts, R.menu.order, R.menu.category_order,
        R.menu.visible, R.menu.disabled

    };
   
     private static final String sMenuExampleNames[] = {
        "Title only", "Title and Icon", "Submenu", "Groups",
        "Checkable", "Shortcuts", "Order", "Category and Order",
        "Visible", "Disabled"
    };
   
    private Spinner mSpinner;
    private TextView mInstructionsText;
    private Menu mMenu;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
       
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, sMenuExampleNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner = new Spinner(this);

        mSpinner.setId(R.id.spinner);
        mSpinner.setAdapter(adapter);
       
        layout.addView(mSpinner,
                new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.FILL_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));

        mInstructionsText = new TextView(this);
        mInstructionsText.setText(getResources().getString(
                R.string.menu_from_xml_instructions_press_menu));
       
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(10, 10, 10, 10);
        layout.addView(mInstructionsText, lp);
       
        setContentView(layout);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        mMenu = menu;
       
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(sMenuExampleResources[mSpinner.getSelectedItemPosition()], menu);
       
        mSpinner.setEnabled(false);
       
        mInstructionsText.setText(getResources().getString(
                R.string.menu_from_xml_instructions_go_back));
       
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.jump:
                Toast.makeText(this, "Jump up in the air!", Toast.LENGTH_SHORT).show();
                return true;

            case R.id.dive:
                Toast.makeText(this, "Dive into the water!", Toast.LENGTH_SHORT).show();
                return true;

            case R.id.browser_visibility:
                final boolean shouldShowBrowser = !mMenu.findItem(R.id.refresh).isVisible();
                mMenu.setGroupVisible(R.id.browser, shouldShowBrowser);
                break;
               
            case R.id.email_visibility:
                final boolean shouldShowEmail = !mMenu.findItem(R.id.reply).isVisible();
                mMenu.setGroupVisible(R.id.email, shouldShowEmail);
                break;
               
            default:
                if (!item.hasSubMenu()) {
                    Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
                    return true;
                }
                break;
        }
       
        return false;
    }

'old > API_Demo' 카테고리의 다른 글

APP_Notification_NotifyingServiceController  (0) 2010.03.23
APP_Notification_IncomingMessageView  (0) 2010.03.23
APP_LauncherShortcuts  (0) 2010.03.23
APP_Intents  (0) 2010.03.23
APP_Dialog_AlertDialogSamples  (0) 2010.03.22
Posted by jazzlife
,

APP_LauncherShortcuts

old/API_Demo 2010. 3. 23. 15:59

    private static final String EXTRA_KEY = "com.example.android.apis.app.LauncherShortcuts";

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        final Intent intent = getIntent();
       final String action = intent.getAction();

        if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
            setupShortcut();
            finish();
            return;
        }

        setContentView(R.layout.launcher_shortcuts);

        TextView intentInfo = (TextView) findViewById(R.id.txt_shortcut_intent);
        String info = intent.toString();
        String extra = intent.getStringExtra(EXTRA_KEY);
        if (extra != null) {
            info = info + " " + extra;
        }
        intentInfo.setText(info);
    }

    private void setupShortcut() {

        Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
        shortcutIntent.setClassName(this, this.getClass().getName());
        shortcutIntent.putExtra(EXTRA_KEY, "ApiDemos Provided This Shortcut");

        Intent intent = new Intent();
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.shortcut_name));
        Parcelable iconResource = Intent.ShortcutIconResource.fromContext(
                this,  R.drawable.app_sample_code);
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);

        setResult(RESULT_OK, intent);
    }
}

'old > API_Demo' 카테고리의 다른 글

APP_Notification_IncomingMessageView  (0) 2010.03.23
APP_Menu_InflateFromXML  (0) 2010.03.23
APP_Intents  (0) 2010.03.23
APP_Dialog_AlertDialogSamples  (0) 2010.03.22
APP_Alarm_AlarmService  (0) 2010.03.22
Posted by jazzlife
,

APP_Intents

old/API_Demo 2010. 3. 23. 13:16
[Intents.java]

    private OnClickListener mGetMusicListener = new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
          intent.setType("audio/*");
          startActivity(Intent.createChooser(intent, "Select music"));
        }
    };


'old > API_Demo' 카테고리의 다른 글

APP_Menu_InflateFromXML  (0) 2010.03.23
APP_LauncherShortcuts  (0) 2010.03.23
APP_Dialog_AlertDialogSamples  (0) 2010.03.22
APP_Alarm_AlarmService  (0) 2010.03.22
APP_Alarm_AlarmController  (0) 2010.03.16
Posted by jazzlife
,

[Alarm Service.java]

 private OnClickListener mStartAlarmListener = new OnClickListener() {
        public void onClick(View v) {

            long firstTime = SystemClock.elapsedRealtime();

            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                            firstTime, 30*1000, mAlarmSender);

            Toast.makeText(AlarmService.this, R.string.repeating_scheduled,
                    Toast.LENGTH_LONG).show();
        }
 

  };

    private OnClickListener mStopAlarmListener = new OnClickListener() {
        public void onClick(View v) {
 
            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
            am.cancel(mAlarmSender);

               Toast.makeText(AlarmService.this, R.string.repeating_unscheduled,
                    Toast.LENGTH_LONG).show();

        }
    };

}



[Manifest.xml]

<service android:name=".app.AlarmService_Service" android:process=":remote" />

        <activity android:name=".app.AlarmService" android:label="@string/activity_alarm_service">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.SAMPLE_CODE" />
            </intent-filter>
        </activity>


 

'old > API_Demo' 카테고리의 다른 글

APP_Intents  (0) 2010.03.23
APP_Dialog_AlertDialogSamples  (0) 2010.03.22
APP_Alarm_AlarmController  (0) 2010.03.16
APP_Activity_Wallpaper  (0) 2010.03.16
APP_Activity_TranslucentBlurActivity  (0) 2010.03.16
Posted by jazzlife
,