(manifest.xml 에서 application activity 추가해줘야됨) 




  main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="이동" />
    <Button
        android:id="@+id/button02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="데이터를 갖고 이동" />

</LinearLayout>


main_two.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>


manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kr.android.intent.msg"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".IntentMsg"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>


package kr.android.intent.msg;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class IntentMsg extends Activity implements View.OnClickListener{
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Button button = (Button)findViewById(R.id.button01);
		Button button2 = (Button)findViewById(R.id.button02);

		button.setOnClickListener(this);
		button2.setOnClickListener(this);
	}
	public void onClick(View v){
		Intent i = null;
		if(v.getId() == R.id.button01){
			i = new Intent(this,IntentTwo.class);
		}else if(v.getId() == R.id.button02){
			//Intent에 실행시킬 Activity 정보 저장
			i = new Intent(this,IntentTwo.class);
			//실행 시킨 Activity에서 사용할 데이터 셋팅
			//사용할 데이터는 Bundle 객체가 생성된후 그 곳에 보관됨
			i.putExtra("msg", "인텐트로 전달된 데이터");
		}
		//Intent객체가 가지고 있는 Activity 정보를 이용해서 Activity 생성,실행
		startActivity(i);
	}
}


package kr.android.intent.msg;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class IntentTwo extends Activity{
	TextView view;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_two);
		view = (TextView)findViewById(R.id.text);
		view.setText("intentTwo 화면\n");

		Intent i = getIntent();
		if(i.getExtras() == null){
			view.append("데이터 없이 화면 이동");
		}else{
			//Activity 실행시 데이터를 저장했다면 Bundle 객체로 부터 데이터 추출
			Bundle b = i.getExtras();
			String str = b.getString("msg");
			view.append(str);
		}
	}
}






위치기반 서비스 어플리케이션을 만든다면 이 기능은 일반적으로 써야 될겁니다 

                           

사용된 이미지(이미지는 res\mdpi 폴더에 넣으면 됩니다)



기본적으로 manifest에서 apllication -> uses library -> 구글맵 선택( 이전게시물 참고) 해야됩니다




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.google.android.maps.MapView
        android:id="@+id/map"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey=""
        android:clickable="true" />

</LinearLayout>


package com.commonsware.android.maps;

import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;

import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.MapView.LayoutParams;

public class NooYawk extends MapActivity {
	MapView map;

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

		map = (MapView) findViewById(R.id.map);

		// 위도와 경도 정보를 갖는 GeoPoint 객체 생성
		GeoPoint gp = getPoint(40.76793169992044, -73.98180484771729);

		// 위치 (내위치 또는 기준이 되는 위치)를 표시하는 마커를 생성
		MapView.LayoutParams mapParams = new MapView.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, gp,
				MapView.LayoutParams.CENTER);

		ImageView iv = new ImageView(getApplicationContext());
		iv.setImageResource(R.drawable.mymarker);
		map.addView(iv, mapParams);

		// 내위치 또는 기준이 되는 위치를 중심으로 표시되는 아이템
		//        (표시해 주고 싶은 좌표위치 정보(예:관공서)표시
		Drawable marker = getResources().getDrawable(R.drawable.marker);

		marker.setBounds(0, 0, marker.getIntrinsicWidth(),
				marker.getIntrinsicHeight());

		// getOverlays() : 지도위에 오버레이될 아이템을 표시하고 
		//               레이어를 추가하기 위해 레이어 목록 호출
		map.getOverlays().add(new SitesOverlay(marker));

		// 줌 레벨을 제거하는 Controll 표시 여부
		map.setBuiltInZoomControls(true);

		// 지정된 위치 정보를 갖는 지도를 표시
		MapController controller = map.getController();
		controller.setCenter(gp);
		controller.setZoom(17);
	}

	private GeoPoint getPoint(double lat, double lon) {
		return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	// ItemizedOverlay : 지도에 보여질 아이템(좌표,제목,간단 설명)의 오버레이 정보처리
	// 각 좌표에 마커를 표시 각 아이템의 스크린 탭( 부가정보 링크)
	// OverlayItem : iItemizedOverlay 클래스에 제공되는 기본 아이템 정보

	private class SitesOverlay extends ItemizedOverlay<overlayitem> {
		private Drawable marker = null;
		private List<overlayitem> items = new ArrayList<overlayitem>();

		public SitesOverlay(Drawable marker) {
			super(marker);
			this.marker = marker;

			items.add(new OverlayItem(getPoint(40.748963847316034,
					-73.96807193756104), "UN", "United Nations"));
			items.add(new OverlayItem(getPoint(40.76866299974387,
					-73.98268461227417), "Lincoln Center",
					"Home of Jazz at Lincoln Center"));
			items.add(new OverlayItem(getPoint(40.765136435316755,
					-73.97989511489868), "Carnegie Hall",
					"Where you go with practice, practice, practice"));
			items.add(new OverlayItem(getPoint(40.70686417491799,
					-74.01572942733765), "The Downtown Club",
					"Original home of the Heisman Trophy"));

			// 생성된 OverlayItem 을 목록으로 지정
			populate();
		}

		// 지정한 번호에 대해 OverlayItem을 return
		@Override
		protected OverlayItem createItem(int i) {
			return items.get(i);
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			super.draw(canvas, mapView, shadow);
			// 마커의 아래의 중간 부분이 좌표에 위치하도록 지정
			boundCenterBottom(marker);
		}

		@Override
		protected boolean onTap(int i) {
			Toast.makeText(NooYawk.this, items.get(i).getSnippet(),
					Toast.LENGTH_SHORT).show();
			return true;
		}
		//레이어가 처리할 수 있는 항목의 개수를 리턴
		@Override
		public int size() {
			return items.size();
		}
	}
}



manifext.xml 에 Uses Library 셋팅을 해야합니다


Uses Library(manifext -> application)



apiKey는 자신의 apikey를 입력하면 됩니다


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.google.android.maps.MapView
        android:id="@+id/map"
        android:clickable="true"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey="" />

</LinearLayout>


GeoPoint값을 자신이 직접 지정할 위치로 해도 됩니다 이전 게시물 참고
package kr.android.map;

import android.os.Bundle;
import android.widget.ImageView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;

public class GoogleMaps extends MapActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		MapView mapView = (MapView) findViewById(R.id.map);
		
		//위도, 경도 정보를 갖는 객체 생성
		//위도, 경도는 실수 정보를 갖는데 연산 속도를 높이기 위해서 정수로 변환시켜 처리
		GeoPoint gp = new GeoPoint((int) (27.173095 * 1000000.0),
				(int) (78.04209 * 1000000.0));
		
		//지도에 마커를 표시하기 위해서 LayoutParams 객체 생성
		MapView.LayoutParams mapParams = new MapView.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, gp,
				MapView.LayoutParams.CENTER);
		
		//마커 정보를 갖는 ImageView 객체 생성
		ImageView iv = new ImageView(getApplicationContext());
		iv.setImageResource(R.drawable.marker);
		
		//MapView에 마커 표시를 위해 ImageView와 LayoutParams객체 등록
		mapView.addView(iv, mapParams);
		
		//지정한 위도와 경도를 보여주는 지도를 화면에 출력
		mapView.getController().animateTo(gp);
		
		//줌레벨 지정(배율 1~ 21 )
		mapView.getController().setZoom(16);
		
		//줌 레벨을 조정할 수 있는 Control 사용 여부 셋팅
		mapView.setBuiltInZoomControls(true);

	}
	@Override
	protected boolean isRouteDisplayed() {
		// 사용하지 않음(추상 메소드)
		//두 지점간의 거리 표시를 위한 메소드
		return false;
	}
}




자신의 버젼의 GoogleApis by Google Inc 클릭



동의



새로만들기



새로만든 AVD실행




기능 확인 






밑에서는 자신의 위치 (경도,위도를 뽑아내기 위함입니다)알기 위해서


구글 접속 

좌측 하단 한국 구글 말고 미국 구글로 들어간다.




위에 메뉴에 Maps 클릭


자신이 얻고자 하는 위치 검색후 위치에 오른쪽 마우스 누르고 What's here? 누르면


위도 경도 값이 나옴











CMD 실행( 시작 -> 실행 -> CMD 입력)


cd .android




keytool -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android


CMD 창에 복사하기 위해선 오른쪽 마우스를 누르면 표시가 나옵니다





http://code.google.com/intl/ko/android/maps-api-signup.html




로그인후 api 키를 발급 받으면 됩니다

'Android > 기본' 카테고리의 다른 글

구글맵에 마커 표시하기(위치 지정)  (0) 2012.04.28
구글맵 사용하기  (0) 2012.04.28
SQLite  (0) 2012.04.28
SD CARD (SD 카드에 저장하기)  (0) 2012.04.28
Access Web Image  (0) 2012.04.28



'Android > 기본' 카테고리의 다른 글

구글맵 사용하기  (0) 2012.04.28
이클립스 구글맵 api 설치하기 및 자신의 위치 알아내기(경도,위도)  (0) 2012.04.28
SD CARD (SD 카드에 저장하기)  (0) 2012.04.28
Access Web Image  (0) 2012.04.28
Read JSON  (0) 2012.04.28
manifest.xml 에서 권한설정을 해줍니다 WRITE_EXTERNAL_STORAGE



SD Card 값 안줬으면은 에뮬끄고 수정누른뒤 512정도로 용량 확보하고 시작합니다



<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/output" />

</LinearLayout>


package kr.android.sdcard;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;

public class SDCardDemo extends Activity {

	// 파일의 이름 생성

	String fileName = "test-" + System.currentTimeMillis() + ".txt";
	private TextView readOutput;

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

		this.readOutput = (TextView) this.findViewById(R.id.output);

		// 파일 생성
		wirteFileToSDcard();
		// 파일 읽기
		readFileFromSDcard();
	}

	private void wirteFileToSDcard() {
		readOutput.setText("[파일쓰기]\n");
		// /sdcard 디렉토리에 대한 참조 설정
		File sdDir = new File("/sdcard");

		if (sdDir.exists() && sdDir.canWrite()) {
			// 경로 설정
			File uadDir = new File(sdDir.getAbsolutePath() + "/filetest");
			uadDir.mkdir(); // mkdir()를 사용하여 디렉토리 생성
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(uadDir.getAbsolutePath() + "/"
						+ fileName);
				String msg = "즐거운 하루!!"; // 파일에 기술될 내용
				fos.write(msg.getBytes());
				readOutput.append("파일이 생성되었습니다.\n");
			} catch (FileNotFoundException e) {
				Toast.makeText(this, "생성된 파일이 없습니다,", 4000).show();
			} catch (IOException e) {
				Toast.makeText(this, "파일에 내용을 기록중 오류 발생", 4000).show();
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	private void readFileFromSDcard() {
		readOutput.append("[파일 읽기]\n");
		File rFile = new File(Environment.getExternalStorageDirectory()
				+ "/filetest/" + fileName);
		//존재하고 읽을 수 있으면 실행
		if (rFile.exists() && rFile.canRead()) {
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(rFile);
				byte[] reader = new byte[fis.available()];
				fis.read(reader);
				readOutput.append(new String(reader));
			} catch (IOException e) {
				Toast.makeText(this, "파일을 읽을 수 없습니다", 4000).show();
			} finally {
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}



'Android > 기본' 카테고리의 다른 글

이클립스 구글맵 api 설치하기 및 자신의 위치 알아내기(경도,위도)  (0) 2012.04.28
SQLite  (0) 2012.04.28
Access Web Image  (0) 2012.04.28
Read JSON  (0) 2012.04.28
XML Resource  (0) 2012.04.28
권한설정 >INTERNET해야됩니다
<?xml version="1.0" encoding="utf-8"?>
<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/do_action"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Go!" />
        <TextView
            android:id="@+id/text"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Press button for action" />            
<ImageView 
     android:id="@+id/ImageView01" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content">
</ImageView>
</LinearLayout>


package kr.android.webimage;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class AccessWebImage extends Activity {
	private static final String TAG="AccessWebImage";
	TextView textView;
	ImageView imageView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        textView = (TextView)findViewById(R.id.text);
        imageView = (ImageView)findViewById(R.id.ImageView01);
        
        Button goButton =(Button)findViewById(R.id.do_action);
        goButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {		
				try{
					URL Text = new URL("http://postfiles9.naver.net/20110412_24/jms8641_13025950287563LdPD_JPEG/%BE%C6%C0%CC%C0%AF1.JPG?type=w1");
					
					Bitmap img = getRemoteImage(Text);
					imageView.setImageBitmap(img);
				}catch(Exception e){
					Log.e(TAG, "Erro in network call",e);
				}
			}
		});
    }
    private Bitmap getRemoteImage(URL url){
    	Bitmap bitmap = null;
    	try{
    		//지정한 URL을 통해서 InputStream(URL의 이미지 정보) 생성 
    		BufferedInputStream bis=
    				new BufferedInputStream(url.openStream());
    		//InputStream -> Bitmap
    		bitmap=BitmapFactory.decodeStream(bis);
    		//닫기
    		bis.close();
    	}catch(IOException e){
    		e.printStackTrace();
    	}
    	return bitmap;
    }
}



'Android > 기본' 카테고리의 다른 글

SQLite  (0) 2012.04.28
SD CARD (SD 카드에 저장하기)  (0) 2012.04.28
Read JSON  (0) 2012.04.28
XML Resource  (0) 2012.04.28
StaticFile  (0) 2012.04.28

assets 폴더에 sample.json 생성





{ 
     "menu":"회원관리", 
     "member":[ 
           { 
                 "id":"dragon", 
                 "name":"홍길동", 
                 "address":"서울시", 
                 "job":"학생" 
           }, 
           { 
                 "id":"sky", 
                 "name":"장영실", 
                 "address":"부산시", 
                 "job":"직장인"  
           } 
       ] 
} 


sample.json 파일정보





<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/text"/>

</LinearLayout>


package kr.android.json;


import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.AssetManager.AssetInputStream;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;


public class ReadJSONDemo extends Activity {


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

		TextView text=(TextView)findViewById(R.id.text);

		//assets 폴더의 내용을 가져오기
		AssetManager assetManager= getResources().getAssets();

		try{
			//사용하고자 하는 json 파일 open , InputStream 반환
			AssetInputStream ais =(AssetInputStream)assetManager.open("sample.json");

			BufferedReader br= new BufferedReader(new InputStreamReader(ais,"utf-8"));

			StringBuffer sb=new StringBuffer();
			String result =null;

			while((result=br.readLine())!= null){
				sb.append(result);
			}
			//JSONObject 생성
			JSONObject jsonObject=new JSONObject(sb.toString());

			String menu = jsonObject.getString("menu");
			text.append(menu+"\n");

			//JSONArray
			JSONArray jArray = new JSONArray(jsonObject.getString("member"));

			for(int i=0;i<jArray.length();i++){
				text.append("============================\n");
				text.append(jArray.getJSONObject(i).getString("id")+"\n");
				text.append(jArray.getJSONObject(i).getString("name")+"\n");
				text.append(jArray.getJSONObject(i).getString("address")+"\n");
				text.append(jArray.getJSONObject(i).getString("job")+"\n");
			}
		}catch(JSONException e){
			Log.e("ReadJSONDemo",e.toString());
		}catch(Exception e){
			Log.e("ReadJSONDemo",e.toString());
		}
	}
}


ㅏㅏ


'Android > 기본' 카테고리의 다른 글

SD CARD (SD 카드에 저장하기)  (0) 2012.04.28
Access Web Image  (0) 2012.04.28
XML Resource  (0) 2012.04.28
StaticFile  (0) 2012.04.28
Read Write File (자동 저장할때 사용)  (0) 2012.04.28
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent" >
	<TextView
		android:id="@+id/selection"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
	/>
	<ListView
		android:id="@android:id/list"
		android:layout_width="fill_parent" 
		android:layout_height="fill_parent"
		android:drawSelectorOnTop="false"
	/>
</LinearLayout>


package com.commonsware.android.resources;

import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class XMLResourceDemo extends ListActivity {
	TextView selection;
	ArrayList<string> items=new ArrayList<string>();
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        selection=(TextView)findViewById(R.id.selection);
        
        try{
        	XmlPullParser xpp =getResources().getXml(R.xml.words);
        	while(xpp.getEventType()!=XmlPullParser.END_DOCUMENT){
        		if(xpp.getEventType()==XmlPullParser.START_TAG){
        			if(xpp.getName().equals("word")){
        				items.add(xpp.getAttributeValue(0));
        			}
        		}
        		
        		xpp.next();
        	}
        }
        catch(Throwable t){
        	Toast.makeText(this, "실패 : "+t.toString(),4000).show();
        }
        setListAdapter(new ArrayAdapter<string>(this,android.R.layout.simple_list_item_1,items));
    }
    
    public void onListItemClick(ListView parent, View v , int position, long id){
    	selection.setText(items.get(position).toString());
    }
}



'Android > 기본' 카테고리의 다른 글

Access Web Image  (0) 2012.04.28
Read JSON  (0) 2012.04.28
StaticFile  (0) 2012.04.28
Read Write File (자동 저장할때 사용)  (0) 2012.04.28
Access Web  (0) 2012.04.28

47staticfiledemo2는 raw폴더 생성 하고 product.xml생성을 해야함

                                       46은 raw -> words.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent" >
	<TextView
		android:id="@+id/selection"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
	/>
	<ListView
		android:id="@android:id/list"
		android:layout_width="fill_parent" 
		android:layout_height="fill_parent"
		android:drawSelectorOnTop="false"
	/>
</LinearLayout>


<words>
	<word value="lorem" />
	<word value="ipsum" />
	<word value="dolor" />
	<word value="sit" />
	<word value="amet" />
	<word value="consectetuer" />
	<word value="adipiscing" />
	<word value="elit" />
	<word value="morbi" />
	<word value="vel" />
	<word value="ligula" />
	<word value="vitae" />
	<word value="arcu" />
	<word value="aliquet" />
	<word value="mollis" />
	<word value="etiam" />
	<word value="vel" />
	<word value="erat" />
	<word value="placerat" />
	<word value="ante" />
	<word value="porttitor" />
	<word value="sodales" />
	<word value="pellentesque" />
	<word value="augue" />
	<word value="purus" />
</words>


package om.commonsware.android.files2;

import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class StaticFileDemo extends ListActivity {
	TextView selection;
	ArrayList<string> items = new ArrayList<string>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        selection = (TextView)findViewById(R.id.selection);
        
        try{
        	//raw\words.xml 을 읽어들여서 InputStream으로 반환
        	InputStream in = getResources().openRawResource(R.raw.words);
        	//Dom 파서 생성
        	DocumentBuilder builder =DocumentBuilderFactory
        			.newInstance()
        			.newDocumentBuilder();
        	//Dom파서가 전달된 InputStream을 읽어 들이고 파싱해서 메모리상에 Dom 트리 생성
        	Document doc = builder.parse(in);
        	//word Element명을 검색해서 같은 레벨에 Element들을 nodeList로 반환
        	NodeList words = doc.getElementsByTagName("word");
        	
        	for(int i=0;i<words.getlength();i++){ 
        		items.add(((element)words.item(i)).getattribute("value"));="" 
        				}="" in.close();="" }catch(throwable="" t){
        					="" toast.maketext(this,"exception="" :="" "+
        				t.tostring(),2000).show();="" setlistadapter(new="" arrayadapter
        				<string="">(this,android.R.layout.simple_list_item_1,items));
        	}
    }
    
    public void onListItemClick(ListView parent,View v, int position,long id){
    	selection.setText(items.get(position).toString());
    }
}






<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/parse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Parse XML" />

	<EditText
	    android:id="@+id/result"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent"
	    android:scrollbars="vertical"
	    android:textSize="20sp"
	    android:gravity="top" />
</LinearLayout>
<?xml version="1.0" encoding="UTF-8"?>
<order>
	<item>Mouse</item>
	<item>Computer</item>
	<item>Android</item>
	<item>IPhone</item>

</order>
package com.commonsware.android.files3;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class StaticFileDemo2 extends Activity implements View.OnClickListener {
	EditText mResult;
	Document doc;

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

		mResult = (EditText) findViewById(R.id.result);

		Button btn = (Button) findViewById(R.id.parse);
		btn.setOnClickListener(this);

		try {
			//raw\product.xml를 읽어들여 InputStream 반환
			InputStream in = getResources().openRawResource(R.raw.product);
			//Dom 파서 생성
			DocumentBuilder builder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			//product.xml 을 읽어들인 InputStream을 파싱해서
			//메모리에 DOM 트리 생성
			doc = builder.parse(in);
		} catch (Exception e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
		}
	}

	public void onClick(View v) {
		StringBuffer sb = new StringBuffer();
		NodeList items = doc.getElementsByTagName("item");

		sb.append("주문 항목\n");
		for (int i = 0; i < items.getLength(); i++) {
			String itemName = items.item(i).getFirstChild().getNodeValue();
			sb.append((i + 1) + " : " + itemName + "\n");
		}
		mResult.setText(sb.toString());
	}
}



'Android > 기본' 카테고리의 다른 글

Read JSON  (0) 2012.04.28
XML Resource  (0) 2012.04.28
Read Write File (자동 저장할때 사용)  (0) 2012.04.28
Access Web  (0) 2012.04.28
NetWork Wifi , 3G  (0) 2012.04.28
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button android:id="@+id/close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="닫기" />
  
    <EditText
        android:id="@+id/editor"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:singleLine="false"
        android:gravity="top" />

</LinearLayout>
package com.commonsware.android.files;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ReadWriteFileDemo extends Activity {
	private final static String NOTES="notes.txt";
	private final static String TAG = "ReadWriteFiledemo";
	private EditText editor;

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

		editor = (EditText)findViewById(R.id.editor);

		Button btn = (Button)findViewById(R.id.close);

		btn.setOnClickListener(new Button.OnClickListener(){

			public void onClick(View v) {
				//액티비티 종료
				//액티비티 종료시에 Activity 생명주기에 의해서 
				//onPause -> onStop -> onDestroy
				finish();
			}
		});
	}
	public void onResume(){
		super.onResume();


		try{
			InputStream in = openFileInput(NOTES);

			if(in!=null){
				InputStreamReader tmp = new InputStreamReader(in);
				BufferedReader reader = new BufferedReader(tmp);
				String str;
				StringBuffer buf = new StringBuffer();

				while((str = reader.readLine()) != null){
					buf.append(str+"\n");
				}
				in.close();
				editor.setText(buf.toString());
			}
		}catch(java.io.FileNotFoundException e){
			Log.e(TAG, "파일을 호출할 수 없습니다.",e);
		}catch(Throwable t){
			Log.e(TAG, "오류 발생",t);
			Toast.makeText(this,"예외 : "+t.toString(),2000)
			.show();
		}
	}
	public void onPause(){
		super.onPause();
		try{
			OutputStreamWriter out = new OutputStreamWriter(openFileOutput(NOTES,0));
			//MODE_PRIVATE :덮어쓰기
			//MODE_APPEND : 이어쓰기
			out.write(editor.getText().toString());
			out.close();
			Toast.makeText(this,"데이터를 저장합니다잉~~",4000).show();
		}catch(Throwable t){
			Toast.makeText(this,"예외 : "+t.toString(),2000).show();
		}
	}
}

이 기능은 데이터를 저장하는 어플리케이션에 모두(거의?) 적용되어 있지만 사용자의 불안함(?) 때문에 자동저장이 있어도 저장버튼을 따로 둔다고함


'Android > 기본' 카테고리의 다른 글

XML Resource  (0) 2012.04.28
StaticFile  (0) 2012.04.28
Access Web  (0) 2012.04.28
NetWork Wifi , 3G  (0) 2012.04.28
Browser WebView (브라우저)  (0) 2012.04.28
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/do_action"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go!" />
	<TextView
	    android:id="@+id/text"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Press button for action" />
	<EditText
	    android:id="@+id/edit"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent" />
</LinearLayout>


package kr.android.web;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AccessWebDemo extends Activity {
	//로그 작성시 검색용 태그
	public static final String TAG="AccessWebDemo";

	BufferedReader br;
	TextView textView;
	EditText edit;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		textView = (TextView)findViewById(R.id.text);
		edit = (EditText)findViewById(R.id.edit);

		Button goButton = (Button)findViewById(R.id.do_action);
		goButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//다량의 문자열 가공시 하나의 객체에서 문자열 처리를 하기위해서 
				StringBuffer sb = new StringBuffer();
				try{
					//인터넷 주소 정보를 갖고 있는 객체
					URL text = new URL("http://www.naver.com/index.html");
					//설정한 인터넷 주소의 HTML 정보를 InputStream으로 반환
					InputStream isText = text.openStream();
					br = new BufferedReader(new InputStreamReader(isText));

					String str = null;
					while((str=br.readLine()) != null){
						sb.append(str+ "\n");
					}

					edit.setText(sb.toString());
					isText.close();
				}catch(Exception e){
					Log.e(TAG,"Error in network call",e);
				}
			}
		});
	}
}




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/do_action"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go!" />
	<TextView
	    android:id="@+id/text"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Press button for action" />
	<EditText
	    android:id="@+id/edit"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent" />
</LinearLayout>



package kr.android.web2;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AccessWebDemo2 extends Activity {
	public static final String TAG="AcessWebdemo";
	
	EditText edit;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        edit = (EditText)findViewById(R.id.edit);
        
        Button goButton = (Button)findViewById(R.id.do_action);
        
        goButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				try{
					String msg = getStringFromURL("http://m.naver.com/index.html");
					edit.setText(msg);
				}catch(Exception e){
					Log.e(TAG,"Error in network call", e);
				}
			}
		});
    }
    public String getStringFromURL(String url){
		String responseBody = null;
		try{
			//전달되는 URL을 통해서 해당 URL을 처리하는 
			//서버에 접속하여 URL에 매칭되어 있는 HTML 정보를 처리하는 객체
			HttpClient httpclient = new DefaultHttpClient();
			
			//HTTPGet : URL를 제공해서 client의 요청 정보 처리(HTML get방식으로 요청)
			//ResponseHandler : 서버로부터 client에 전달되는 응답 정보 처리(HTML 추출)
			
			ResponseHandler<string> responseHander = new BasicResponseHandler();
			responseBody = httpclient.execute(new HttpGet(url), responseHander);
		}catch(Exception e){
			Log.e(TAG,"getStringFromURL error",e);
		}
    	return responseBody;
    }
}





<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/do_action"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go!" />
	<TextView
	    android:id="@+id/text"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="Press button for action" />
	<EditText
	    android:id="@+id/edit"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent" />
</LinearLayout>



package kr.android.web3;

import java.io.BufferedReader;

import kr.android.web3.R;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AccessWebDemo3 extends Activity {
	public static final String TAG = "AcessWebdemo";
	BufferedReader br;
	TextView textView;
	EditText edit;
	ProgressDialog dialog;

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

		edit = (EditText) findViewById(R.id.edit);
		textView = (TextView) findViewById(R.id.text);

		Button goButton = (Button) findViewById(R.id.do_action);

		goButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				/*백그라운드에서 웹에 접속해서 HTML을 전송하는 동안 UI에 데이터 전송중임을 알리는 
				메세지를 출력하는 기능
				원격 데이터 전송받는 순서
				1. ProgressDialog 생성
				2. 백그라운드에서 HTML를 전송받음
				3. 전송이 완료되면 ProgressDialog 중지
				4. UI 갱신*/
				dialog = ProgressDialog.show(AccessWebDemo3.this, "사이트 접속중",
						"페이지를 로드중 입니다", true);

				try {
					proccessData();
				} catch (Exception e) {
					Log.e(TAG, "Error in network call", e);
				}
			}

		});
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			//ProgressDialog 중지
			dialog.dismiss();

			//UI 갱신
			String result = msg.getData().getString("str");
			edit.setText(result);
		}
	};

	public void proccessData() {
		//원격 데이터를 전송받기 위해
		//Thread를 생성해 UI가 display되는 동안에 백그라운드에서 데이터를 전송받음
		new Thread() {
			public void run() {
				String str = getStringFromUrl("http://www.naver.com/index.html");

				//Message 객체 생성
				Message message = handler.obtainMessage();
				//전송받은 데이터를 담기 위해 Bundle 객체 생성
				Bundle bundle = new Bundle();
				bundle.putString("str", str);
				//Bundle객체를 Message객체 등록
				message.setData(bundle);
				//Handler의 HandleMessage 메소드 호출
				handler.sendMessage(message);
			}
		}.start();
	}

	public String getStringFromUrl(String url) {
		String responseBody = null;
		try {
			// 전달되는 URL을 통해서 해당 URL을 처리하는
			// 서버에 접속하여 URL에 매칭되어 있는 HTML 정보를 처리하는 객체
			HttpClient httpclient = new DefaultHttpClient();

			// HTTPGet : URL를 제공해서 client의 요청 정보 처리(HTML get방식으로 요청)
			// ResponseHandler : 서버로부터 client에 전달되는 응답 정보 처리(HTML 추출)

			ResponseHandler<string> responseHander = new BasicResponseHandler();
			responseBody = httpclient.execute(new HttpGet(url), responseHander);
		} catch (Exception e) {
			Log.e(TAG, "getStringFromURL error", e);
		}
		return responseBody;
	}
}




마지막에는 데이터를 가지고 올때 로딩이 뜨게 되있습니다

권한 설정은 INTERNET입니다(manifext.xml)


'Android > 기본' 카테고리의 다른 글

StaticFile  (0) 2012.04.28
Read Write File (자동 저장할때 사용)  (0) 2012.04.28
NetWork Wifi , 3G  (0) 2012.04.28
Browser WebView (브라우저)  (0) 2012.04.28
Handler 사용하기 (로딩 표시?)  (0) 2012.04.28

권한 설정을 해줘야함


적용이 되었습니다.



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        
    <TextView
        android:id="@+id/instruct"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Press Button for Action" />
    
    <Button
        android:id="@+id/do_action"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go!" />
        
    </LinearLayout>
    <TextView
        android:id="@+id/status"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
package kr.android.network;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class NetWorkStatusDemo extends Activity {
	TextView status;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        status = (TextView)findViewById(R.id.status);
        
        Button goButton = (Button)findViewById(R.id.do_action);
        
        goButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
				ConnectivityManager cm = 
						(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
				//Wifi 정보 호출
				NetworkInfo ni =cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
				
				//사용 가능 여부
				boolean isWifiAvail = ni.isAvailable();
				
				//접속 여부
				boolean isWifiConn = ni.isConnected();
				
				//모바일(3G) 정보 호출
				ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
				
				//사용 가능 여부
				boolean isMobileAvail = ni.isAvailable();
				
				//접속 여부
				boolean isMobileConn = ni.isConnected();
				
				status.setText("Wifi\n연결가능 =" +isWifiAvail+"\n연결 = " 
				+ isWifiConn+"\nMobile\n연결 가능 ="+isMobileAvail+"\n 연결 ="+isMobileConn);
			}
		});
    }
}



'Android > 기본' 카테고리의 다른 글

Read Write File (자동 저장할때 사용)  (0) 2012.04.28
Access Web  (0) 2012.04.28
Browser WebView (브라우저)  (0) 2012.04.28
Handler 사용하기 (로딩 표시?)  (0) 2012.04.28
Activity 생명주기  (0) 2012.04.28
2번 빼고 permission 권한 INTERNET을 주어야 한다 이전 게시물 참고

간단히 말하면 manifest.xml 접근 -> permission 탭 -> add -> uses -> INTERNET -> 저장

(밑으로 내려갈수록 발전되는 기능을 볼수 있음 )
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/webkit"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    
</LinearLayout>


package com.commonsware.android.browser1;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class BrowserDemo1 extends Activity {
    WebView browser;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        browser = (WebView)findViewById(R.id.webkit);
        
        browser.loadUrl("http://m.naver.com");
        
    }
}





<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/webkit"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>


package com.commonsware.android.browser2;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class BrowserDemo2 extends Activity {
	WebView browser;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        browser = (WebView)findViewById(R.id.webkit);
        
        
        String msg = "<meta http-equiv="\"Content-Type\"" content="\"text/html;" 
        		charset="UTF-8\"">Hello, world! 안녕하세요!";        
        
        browser.loadData(msg,"text/html","UTF-8");
    }
}





<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/web"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>


package com.commonsware.android.browser3;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class BrowserDemo3 extends Activity {
	WebView mWeb;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mWeb = (WebView)findViewById(R.id.web);
        
        mWeb.setWebViewClient(new MyWebClient());
        WebSettings set = mWeb.getSettings();
        set.setJavaScriptEnabled(true);
        set.setBuiltInZoomControls(true);
        mWeb.loadUrl("http://m.nate.com");
    }
    
    //HTML페이지에서 링크를 클릭할 때 발생하는 이벤트를 처리하는 클래스
    class MyWebClient extends WebViewClient{
    	//전달되는 인자
    	//WebView view : 실행중인 WebView 객체
    	//String url : 클릭한 링크(링크를 다시 받아 내부에서 처리)
    	
    	public boolean shouldOverrideUIrlLoading(WebView view, String url){
    		view.loadUrl(url);
    		return true;
    	}
    }
}




'Android > 기본' 카테고리의 다른 글

Access Web  (0) 2012.04.28
NetWork Wifi , 3G  (0) 2012.04.28
Handler 사용하기 (로딩 표시?)  (0) 2012.04.28
Activity 생명주기  (0) 2012.04.28
Message 팝업창 띄우기 경고창,토스트 표시,Progress Dialog  (0) 2012.04.28
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- 막대바 형식의 progress -->
    <ProgressBar android:id="@+id/progress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal" />
    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleLarge" />
    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleSmall" />

</LinearLayout>



package com.commonsware.android.threads;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;

public class HandlerDemo extends Activity {
	ProgressBar bar;
	//백그라운드 작업을 하고 있는 Thread 객체가 데이터를 Message에 담아서
	//전달 받으면 해당메세지로 부터 데이터 추출해서 Activity의 View전달하는 역할
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg){
			bar.incrementProgressBy(5);
		}
	};
	boolean isRunning=false;
	
	//Activity 생명주기
	//onCreate메소드 -> onStart메소드 -> onResume메소드 -> 화면 display
	//화면이 가려질 때는 onPause 메소드 -> onStop메소드
	//화면이 가려졌다 다시 display 될때 onRestart메소드 -> onStart메소드
	//                            -> onResume메소드  -> 화면 display
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		bar=(ProgressBar)findViewById(R.id.progress);
	}
	public void onStart(){
		super.onStart();
		bar.setProgress(0); //Progressbar 초기화

		Thread background=new Thread(new Runnable() {
			public void run(){
				try{
					for (int i=0; i<20 && isRunning; i++){
						Thread.sleep(1000);
						handler.sendMessage(handler.obtainMessage());
					}
				}
				catch(Throwable t){
					//오류가 발생하면 백그라운드 스레드를 그대로 종료한다
				}
			}
		});
		
		isRunning=true;
		background.start();
	}
	public void onStop(){
		super.onStop();
		isRunning=false;
	}
}


기존이미지



수정된 이미지(코드를 더 추가하여 Progress몇개더 구현함
막대의 형태의 progress 


+ Recent posts