[ExpandableList1.java]

public class ExpandableList1 extends ExpandableListActivity {

    ExpandableListAdapter mAdapter;

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

        // Set up our adapter
        mAdapter = new MyExpandableListAdapter();
        setListAdapter(mAdapter);
        registerForContextMenu(getExpandableListView());
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Sample menu");
        menu.add(0, 0, 0, R.string.expandable_list_sample_action);
    }
   
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo();

        String title = ((TextView) info.targetView).getText().toString();
       
        int type = ExpandableListView.getPackedPositionType(info.packedPosition);
        if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
            int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
            int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
            Toast.makeText(this, title + ": Child " + childPos + " clicked in group " + groupPos,
                    Toast.LENGTH_SHORT).show();
            return true;
        } else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
            int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
            Toast.makeText(this, title + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show();
            return true;
        }
       
        return false;
    }


 public class MyExpandableListAdapter extends BaseExpandableListAdapter {
        // Sample data set.  children[i] contains the children (String[]) for groups[i].
        private String[] groups = { "People Names", "Dog Names", "Cat Names", "Fish Names" };
        private String[][] children = {
                { "Arnold", "Barry", "Chuck", "David" },
                { "Ace", "Bandit", "Cha-Cha", "Deuce" },
                { "Fluffy", "Snuggles" },
                { "Goldy", "Bubbles" }
        };
       
        public Object getChild(int groupPosition, int childPosition) {
            return children[groupPosition][childPosition];
        }

        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        public int getChildrenCount(int groupPosition) {
            return children[groupPosition].length;
        }

        public TextView getGenericView() {
            // Layout parameters for the ExpandableListView
            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                    ViewGroup.LayoutParams.FILL_PARENT, 64);

            TextView textView = new TextView(ExpandableList1.this);
            textView.setLayoutParams(lp);
            // Center the text vertically
            textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
            // Set the text starting position
            textView.setPadding(36, 0, 0, 0);
            return textView;
        }
       
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                View convertView, ViewGroup parent) {
            TextView textView = getGenericView();
            textView.setText(getChild(groupPosition, childPosition).toString());
            return textView;
        }

        public Object getGroup(int groupPosition) {
            return groups[groupPosition];
        }

        public int getGroupCount() {
            return groups.length;
        }

        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
                ViewGroup parent) {
            TextView textView = getGenericView();
            textView.setText(getGroup(groupPosition).toString());
            return textView;
        }

        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public boolean hasStableIds() {
            return true;
        }

    }
}

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

Views_Expandable_Simple Adapter  (0) 2010.04.19
Views_Expandable_Cursor [contact]  (0) 2010.04.19
Views_Custom  (0) 2010.04.19
Views_Controls_LightTheme  (0) 2010.04.05
Views_Chronometer  (0) 2010.04.05
Posted by jazzlife
,

Views_Custom

old/API_Demo 2010. 4. 19. 12:16

[custom_view_1.xml]

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res/com.example.android.apis"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
   
    <com.example.android.apis.view.LabelView
            android:background="@drawable/red"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            app:text="Red"/>
   
    <com.example.android.apis.view.LabelView
            android:background="@drawable/blue"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            app:text="Blue" app:textSize="20dp"/>
   
    <com.example.android.apis.view.LabelView
            android:background="@drawable/green"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            app:text="Green" app:textColor="#ffffffff" />

</LinearLayout>



[LabelView.java]

package com.example.android.apis.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import com.example.android.apis.R;

public class LabelView extends View {
    private Paint mTextPaint;
    private String mText;
    private int mAscent;


public LabelView(Context context) {
        super(context);
        initLabelView();
    }

public LabelView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();

         // xml의 attrs를 LabelView 이름으로 가져온다.        
       TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.LabelView);

       // text를 가져와서 s에 setText
       CharSequence s = a.getString(R.styleable.LabelView_text);
        if (s != null) {
            setText(s.toString());
        }

       // color 가져온다. (default값도 설정)
       setTextColor(a.getColor(R.styleable.LabelView_textColor, 0xFF000000));

        // textSize 가져온다.
        int textSize = a.getDimensionPixelOffset(R.styleable.LabelView_textSize, 0);
        if (textSize > 0) {
            setTextSize(textSize);
        }

         //가져온 typedarray 해제
         a.recycle();
    }

    private final void initLabelView() {
        mTextPaint = new Paint();
        mTextPaint.setAntiAlias(true);    // edge 부분을 부드럽게
        mTextPaint.setTextSize(16);
        mTextPaint.setColor(0xFF000000);
        setPadding(3, 3, 3, 3);
    }

public void setText(String text) {
        mText = text;
        requestLayout();    // 갱신       
        invalidate();          // draw 갱신
    }

public void setTextSize(int size) {
        mTextPaint.setTextSize(size);
        requestLayout();    //  갱신
        invalidate();          // draw 갱신
    }

public void setTextColor(int color) {
        mTextPaint.setColor(color);
        invalidate();   // draw 갱신
    }

    // store measure width & height
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureWidth(widthMeasureSpec),
                measureHeight(heightMeasureSpec));
    }

private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = (int) mTextPaint.measureText(mText) + getPaddingLeft()
                    + getPaddingRight();
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }

        return result;
    }


    private int measureHeight(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        mAscent = (int) mTextPaint.ascent();
        if (specMode == MeasureSpec.EXACTLY) {

            result = specSize;
        } else {

            result = (int) (-mAscent + mTextPaint.descent()) + getPaddingTop()
                    + getPaddingBottom();
            if (specMode == MeasureSpec.AT_MOST) {

                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    // text 그리기    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent, mTextPaint);
    }
}

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

Views_Expandable_Cursor [contact]  (0) 2010.04.19
Views_Expandable_Custom Adapter  (0) 2010.04.19
Views_Controls_LightTheme  (0) 2010.04.05
Views_Chronometer  (0) 2010.04.05
View_Buttons  (0) 2010.04.05
Posted by jazzlife
,
[Manifest.xml]

        <activity android:name=".view.Controls1"
                android:label="Views/Controls/1. Light Theme"
                android:theme="@android:style/Theme.Light">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.SAMPLE_CODE" />
            </intent-filter>
        </activity>

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

Views_Expandable_Custom Adapter  (0) 2010.04.19
Views_Custom  (0) 2010.04.19
Views_Chronometer  (0) 2010.04.05
View_Buttons  (0) 2010.04.05
View_AutoComplete_MultipleItems  (0) 2010.04.02
Posted by jazzlife
,

Views_Chronometer

old/API_Demo 2010. 4. 5. 14:06

[ChonometerDemo.java]

Chronometer mChronometer;

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

        setContentView(R.layout.chronometer);

        Button button;

        mChronometer = (Chronometer) findViewById(R.id.chronometer);

        // Watch for button clicks.
        button = (Button) findViewById(R.id.start);
        button.setOnClickListener(mStartListener);

        button = (Button) findViewById(R.id.stop);
        button.setOnClickListener(mStopListener);

        button = (Button) findViewById(R.id.reset);
        button.setOnClickListener(mResetListener);

        button = (Button) findViewById(R.id.set_format);
        button.setOnClickListener(mSetFormatListener);

        button = (Button) findViewById(R.id.clear_format);
        button.setOnClickListener(mClearFormatListener);
    }

    View.OnClickListener mStartListener = new OnClickListener() {
        public void onClick(View v) {
            mChronometer.start();
        }
    };

    View.OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v) {
            mChronometer.stop();
        }
    };

    View.OnClickListener mResetListener = new OnClickListener() {
        public void onClick(View v) {
            mChronometer.setBase(SystemClock.elapsedRealtime());
        }
    };

    View.OnClickListener mSetFormatListener = new OnClickListener() {
        public void onClick(View v) {
            mChronometer.setFormat("Formatted time (%s)");
        }
    };

    View.OnClickListener mClearFormatListener = new OnClickListener() {
        public void onClick(View v) {
            mChronometer.setFormat(null);
        }
    };



[

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

Views_Custom  (0) 2010.04.19
Views_Controls_LightTheme  (0) 2010.04.05
View_Buttons  (0) 2010.04.05
View_AutoComplete_MultipleItems  (0) 2010.04.02
View_AutoComplete_ContactsWithHint  (0) 2010.04.02
Posted by jazzlife
,

View_Buttons

old/API_Demo 2010. 4. 5. 14:04

[buttons_1.xml]

        <!-- Regular sized buttons -->
        <Button android:id="@+id/button_normal"
            android:text="@string/buttons_1_normal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <!-- Small buttons -->
        <Button android:id="@+id/button_small"
            style="?android:attr/buttonStyleSmall"
            android:text="@string/buttons_1_small"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ToggleButton android:id="@+id/button_toggle"
            android:text="@string/buttons_1_toggle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

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

Views_Controls_LightTheme  (0) 2010.04.05
Views_Chronometer  (0) 2010.04.05
View_AutoComplete_MultipleItems  (0) 2010.04.02
View_AutoComplete_ContactsWithHint  (0) 2010.04.02
View_AutoComplete_Contacts  (0) 2010.04.02
Posted by jazzlife
,

'old > sms&mms' 카테고리의 다른 글

SMS framework 소스 참고  (0) 2010.05.10
framework_source 참고  (0) 2010.05.10
telephony framework architecture  (0) 2010.04.26
Network switching subsystem  (0) 2010.03.24
Definitions  (0) 2010.03.18
Posted by jazzlife
,

[AutoComplete6.java]

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

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, COUNTRIES);
        MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.edit);
        textView.setAdapter(adapter);
        textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
    }

    static final String[] COUNTRIES = new String[] {
    "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
    "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
    "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",.... };
}



[autocomplete_6.xml]

        <MultiAutoCompleteTextView android:id="@+id/edit"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

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

Views_Chronometer  (0) 2010.04.05
View_Buttons  (0) 2010.04.05
View_AutoComplete_ContactsWithHint  (0) 2010.04.02
View_AutoComplete_Contacts  (0) 2010.04.02
View_AutoComplete_Scroll  (0) 2010.04.02
Posted by jazzlife
,

[AutoComplete5.java]

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

        ContentResolver content = getContentResolver();
        Cursor cursor = content.query(Contacts.People.CONTENT_URI,
                PEOPLE_PROJECTION, null, null, Contacts.People.DEFAULT_SORT_ORDER);
        AutoComplete4.ContactListAdapter adapter =
                new AutoComplete4.ContactListAdapter(this, cursor);

        AutoCompleteTextView textView = (AutoCompleteTextView)
                findViewById(R.id.edit);
        textView.setAdapter(adapter);
    }



[autocomplete_5.xml]

        <AutoCompleteTextView android:id="@+id/edit"
            android:completionThreshold="1"
            android:completionHint="@string/autocomplete_5_hint"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

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

View_Buttons  (0) 2010.04.05
View_AutoComplete_MultipleItems  (0) 2010.04.02
View_AutoComplete_Contacts  (0) 2010.04.02
View_AutoComplete_Scroll  (0) 2010.04.02
View_AutoComplete_ScreenBottom  (0) 2010.04.02
Posted by jazzlife
,

[AutoComplete4.java]

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

        ContentResolver content = getContentResolver();
        Cursor cursor = content.query(Contacts.People.CONTENT_URI,
                PEOPLE_PROJECTION, null, null, Contacts.People.DEFAULT_SORT_ORDER);
        ContactListAdapter adapter = new ContactListAdapter(this, cursor);

        AutoCompleteTextView textView = (AutoCompleteTextView)
                findViewById(R.id.edit);
        textView.setAdapter(adapter);
    }

    // XXX compiler bug in javac 1.5.0_07-164, we need to implement Filterable
    // to make compilation work
    public static class ContactListAdapter extends CursorAdapter implements Filterable {
        public ContactListAdapter(Context context, Cursor c) {
            super(context, c);
            mContent = context.getContentResolver();
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            final LayoutInflater inflater = LayoutInflater.from(context);
            final TextView view = (TextView) inflater.inflate(
                    android.R.layout.simple_dropdown_item_1line, parent, false);
            view.setText(cursor.getString(5));
            return view;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            ((TextView) view).setText(cursor.getString(5));
        }

        @Override
        public String convertToString(Cursor cursor) {
            return cursor.getString(5);
        }

        @Override
        public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
            if (getFilterQueryProvider() != null) {
                return getFilterQueryProvider().runQuery(constraint);
            }

            StringBuilder buffer = null;
            String[] args = null;
            if (constraint != null) {
                buffer = new StringBuilder();
                buffer.append("UPPER(");
                buffer.append(Contacts.ContactMethods.NAME);
                buffer.append(") GLOB ?");
                args = new String[] { constraint.toString().toUpperCase() + "*" };
            }

            return mContent.query(Contacts.People.CONTENT_URI, PEOPLE_PROJECTION,
                    buffer == null ? null : buffer.toString(), args,
                    Contacts.People.DEFAULT_SORT_ORDER);
        }

        private ContentResolver mContent;       
    }

    private static final String[] PEOPLE_PROJECTION = new String[] {
        Contacts.People._ID,
        Contacts.People.PRIMARY_PHONE_ID,
        Contacts.People.TYPE,
        Contacts.People.NUMBER,
        Contacts.People.LABEL,
        Contacts.People.NAME,
    };
}



[autocomplete_4.xml]

 <AutoCompleteTextView android:id="@+id/edit"
            android:completionThreshold="1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>


 

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

View_AutoComplete_MultipleItems  (0) 2010.04.02
View_AutoComplete_ContactsWithHint  (0) 2010.04.02
View_AutoComplete_Scroll  (0) 2010.04.02
View_AutoComplete_ScreenBottom  (0) 2010.04.02
View_AutoComplete_ScreenTop  (0) 2010.04.02
Posted by jazzlife
,

[autocomplete_3.xml]

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

</ScrollView>


 

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

View_AutoComplete_ContactsWithHint  (0) 2010.04.02
View_AutoComplete_Contacts  (0) 2010.04.02
View_AutoComplete_ScreenBottom  (0) 2010.04.02
View_AutoComplete_ScreenTop  (0) 2010.04.02
Views_Animation_Shake  (0) 2010.03.26
Posted by jazzlife
,

[AutoComplete2.java]

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

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line,
                AutoComplete1.COUNTRIES);
        AutoCompleteTextView textView = (AutoCompleteTextView)
                findViewById(R.id.edit);
        textView.setAdapter(adapter);
    }



[autocomplete_2.xml]

        <AutoCompleteTextView android:id="@+id/edit"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

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

View_AutoComplete_Contacts  (0) 2010.04.02
View_AutoComplete_Scroll  (0) 2010.04.02
View_AutoComplete_ScreenTop  (0) 2010.04.02
Views_Animation_Shake  (0) 2010.03.26
Views_Animation_Push  (0) 2010.03.26
Posted by jazzlife
,

[AutoComplete1.java]

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

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, COUNTRIES);
        AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit);
        textView.setAdapter(adapter);
    }


static final String[] COUNTRIES = new String[] {
 "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
 "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",... }


[audocomplete_1.xml]

        <AutoCompleteTextView android:id="@+id/edit"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>


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

View_AutoComplete_Scroll  (0) 2010.04.02
View_AutoComplete_ScreenBottom  (0) 2010.04.02
Views_Animation_Shake  (0) 2010.03.26
Views_Animation_Push  (0) 2010.03.26
Views_Animation_Interpolators  (0) 2010.03.26
Posted by jazzlife
,

백그라운드 실행

old/Linux 2010. 4. 1. 16:29

빌드서버에서 폰 관련 이미지를 빌드 하실 때 터미널(putty, Xshell )을 통해 하실텐데요.

이게 시간도 많이 걸리고 터미널을 닫았을 시 프로세스가 종료되는 문제가 있습니다.

다음 명령어를 활용해 보세요

 

nohup COMMAND [ARG]...

ex) $ nohup ./build_target.sh&

뒤에 꼭 “&”를 붙이셔야 합니다.

 

이리 하면 &명령어에 의해 백그라운드로 돌면서 터미널이 종료되어도 프로세스를 유지하게 됩니다.

그리고 기타 옵션을 주지 않았을 시 명령어를 실행한 폴더에 nohup.out 이라는 파일이 생성될 겁니다.

이 파일에 실행 시 standard out 으로 출력되는 모든 텍스트 로그를 기록하게 되는데요.

다음 명령어로 로그를 확인 할 수 있습니다.

 

$ tail f ./nohup.out

 

tail은 문서의 끝부터 일정 라인을 보여주는 명령어 인데 –f 옵션으로 append 되는 내용을 추가로 보여줍니다.

tail로 로그를 확인 중 나가고 싶으시면 그냥 Ctrl+C 하시면 되겠습니다. 그 외 자세한 옵션은 man page를 확인 해 보세요.

 

요약)

$ cd android

$ nohup ./build_target.sh &

$ tail f ./nohup.out

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

지정 시간에 동작을 예약하는 명령어 [at 사용법]  (0) 2010.05.08
리눅스용 소스 비교 툴  (0) 2010.04.19
우분투 명령어 정리  (0) 2010.03.25
g++ 과 gdb 사용법  (0) 2010.03.25
프로그램 내에서 쉘 명령어 수행  (0) 2010.03.25
Posted by jazzlife
,

//보이기

InputMethodManager inputMethodManager =
        (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

## 방법은 많은데 이상하게도 제대로 되는 건 이것 하나 뿐이다.


//감추기

InputMethodManager inputMethodManager =
       (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

inputMethodManager.hideSoftInputFromWindow(mTextEditor.getWindowToken(), 0);


 

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

외부 app의 DB와 동기화를 위해서 감시하는 코드  (0) 2010.04.23
Vcard  (0) 2010.03.09
Posted by jazzlife
,

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
,

** 우분투 데스크탑 8.10 기준

** 경로가 빈칸인 명령어는 어디서나 실행가능
** 사용유형이 빈칸인 것은 실행을 뜻함


명령어

경로

사용유형

설명

.bash_history 각 계정의 홈 디렉터리 편집 사용자가 적었던 명령어 기록
.bashrc 각 계정의 홈 디렉터리 편집 단축키 설정
.profile 각 계정의 홈 디렉터리 편집 로그인시 실행될 항목
.vimrc 각 계정의 홈 디렉터리 생성->편집 vi편집기 설정
apt-get     인터넷을 통한 프로그램 설치
at     예약작업
at.allow /etc 편집 특정 계정 at 허용
at.deny /etc 편집 특정 계정 at 거부
atd /etc/init.d   at 데몬
atq     예약 작업 보기
atrm     예약 작업 지우기
bc     계산기
cal     달력
cat     파일 생성, 내용 보기
cd     디렉터리 이동
chage     계정, 암호 만료일자 설정
chattr     속성 변경
chgrp     파일의 그룹 변경
chkconfig   설치->실행 데몬 설정
chmod     파일의 퍼미션 변경
chown     파일의 사용자, 그룹 변경
clear     화면 청소
cp     복사
cpuinfo /proc 편집 cpu 정보 보기
cron /etc/init.d   예약작업 데몬
crontab   편집, 실행 예약작업
date     날짜, 시각 보기
df     전체 용량 보기
dmesg     컴퓨터의 상세한 정보 보기
dpkg     프로그램 설치, 삭제
du     디렉터리별 용량 보기
exit     로그아웃
fdisk     파티션 설정
fg     포그라운드로 불러내기
find     찾기
free     메모리 사용량 확인
fsck.ext3     수동 시스템 검사(꼭 싱글모드에서 해야함)
fstab /etc 편집 마운트 설정
ftp     파일 서버
gcc     컴파일
grep     내용 찾기
group /etc 편집 그룹 보기, 설정
groupadd     그룹 생성
groupdel     그룹 삭제
groupmod     그룹 수정
groups     유저가 속한 그룹 보기
gzip     압축
halt     컴 수동 종료
head     파일내용 앞부분 출력
history     사용 명령어 목록 출력
hosts.allow /etc 편집 호스트 허용
hosts.deny /etc 편집 호스트 차단
id     계정 정보 보기
ifconfig     ip보기, 설정
init     런레벨 실행
interfaces /etc/network 편집 네트워크 설정
issue /etc 편집 로그인전 출력할 내용
jobs     작업 보기
kill     프로세스 종료
last     부팅 로그 보기
lastlog     마지막 접속로그 보기
ln     링크하기
login.defs /etc   계정 번호 설정
logout     로그아웃
ls     파일의 목록 보기
lsattr     속성 보기
man     매뉴얼 보기
mc   설치->실행 탐색기
meminfo /proc 편집 메모리 정보 보기
menu.lst /boot/grub 편집 부팅설정
messages /var/log 편집 로그인 로그 파일
mkdir     디렉터리 생성
more     파일을 페이지 단위로 보기
motd /etc 편집 로그인후 출력할 내용
mount     장치 연결하기
mv     이동, 이름 변경
networking /etc/init.d   네트워크 데몬
passwd /etc 편집 계정 목록
passwd     암호 설정
patch     패치하기
ping     핑 보내기
profile /etc 편집 로그인시 실행될 항목
ps     프로세스 보기
pwconv     쉐도우 패스워드 설정
pwunconv     쉐도우 패스워드 해제
python     파이썬(프로그래밍 언어) 실행
rc.local /etc 편집 부팅시 이 파일 내용을 읽어들임
rcconf   설치->실행 부팅시 데몬 시작 여부 설정
reboot     재부팅
rm     파일, 디렉터리 삭제
rmdir     디렉터리 삭제
rpm   설치->실행 rpm 설치, 제거, 검색
scp     파일 주고받기
service     데몬을 시작시키거나 중지시킨다
shadow /etc 편집 계정 목록(컨버전 안된 암호가 표시됨)
shutdown     컴 끄기
squid /etc/init.d 설치->실행 프록시 서버 데몬
ssh     암호화 지원하는 원격접속 프로그램
su /etc/pam.d 편집 su 설정
su     사용자 변경
tail     파일내용 뒷부분 출력
tar     파일 묶기, 압축
tee     파일로 출력
telnet     원격접속 프로그램
touch     파일 생성
tty     터미널 번호 보기
tune2fs     자동 시스템 검사
umount     마운트 해제
uname     커널 버전 보기
useradd     계정 생성
userdel     계정 삭제
usermod     계정 수정
version /proc 편집 운영체제 버전 보기
vi     편집기
vim     vi편집기 향상판
vipw     vi /etc/passwd
w     시스템에 접속한 사용자 상황 표시
wall     메시지 보내기
who am I     자세한 자신의 정보 보기
whoami     자신의 정보 보기
xinetd /etc/init.d 설치->실행 수퍼 데몬
xinetd.conf /etc 설치->편집 텔넷 설정

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

리눅스용 소스 비교 툴  (0) 2010.04.19
백그라운드 실행  (0) 2010.04.01
g++ 과 gdb 사용법  (0) 2010.03.25
프로그램 내에서 쉘 명령어 수행  (0) 2010.03.25
gcc 옵션  (0) 2010.03.25
Posted by jazzlife
,