- 인터페이스를 이용해서 프래그먼트에서 액티비티로 이벤트를 전달 하는 방법-  

[MainActivity]
public class MainActivity extends AppCompatActivity implements OnListItemSelectedListener{

private static String[] NUMBERS = new String[] { "1", "2", "3", "4", "5" };

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

// 프래그먼트 생성

ArrayListFragment list = new ArrayListFragment();

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(android.R.id.content, list).commit();
}

public void onListItemSelected(String itemName) {
setTitle(getTitle() + " " + itemName);
}

public static class ArrayListFragment extends ListFragment {
OnListItemSelectedListener myListener;

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);

try {
// activity OnListItemSelectedListener 인터페이스가 구현되어 있어야 캐스팅 가능함.
myListener = (OnListItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnListItemSelectedListener interface");
}
}

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

setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1, NUMBERS));
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {

getListView().setItemChecked(position, true);

// 프래그먼트 아이템 클릭시 인터페이스 함수 호출하여 전달
myListener.onListItemSelected(NUMBERS[position]);
}
}
}

 
[OnListItemSelectedListener.java] // 인터페이스
public interface OnListItemSelectedListener {
public void onListItemSelected(String itemName);
}
 


프로그램 내에서 Fragment back stack 을 사용하여 뒤로가기시 순차적으로(LIFO) 보여주려고 하였으나, 정상적으로 동작하지 않음.

AppCompatActivity 를 사용한 뒤 발생 하는 듯 하다.


FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.content, fragment);
ft.addToBackStack(null);

'addToBackStack()' 처리를 하였으나, 프래그먼트가 순차적으로 보이지 않고 activity 종료 됨.


'onBackPress()' 를 오버라이드 하여 해결함.

프래그먼트를 생성한 activity 에서 override 함

@Override
public void onBackPressed() {
if(getFragmentManager().getBackStackEntryCount() > 0){
getFragmentManager().popBackStack();
}
else{
super.onBackPressed();
}
}



managedQuery 의 경우 API Level 11 부터 deprecated 되었다.

아래와 같이 변경해서 사용해야 한다.

ex) managedQuery() ==> getContentResolver().query()


(*변경전)



Cursor contactsCursor = this.managedQuery(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

 



(*변경후)



Cursor contactsCursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
 


startManaginCursor() 또한 사용할 수 없으므로(Deprecated) Cursor 관리를 개발자가 하던지, LoaderManager 클래스를 사용하여야 한다.

managedQuery() 와 startManagingCursor() 가 deprecated 되면서 대체 사용이 가능한 LoaderManager 와 CursorLoader 를 이용한 간단한 예제



. 주소록 접근 및 리스트뷰로 가져오기

1. 'implements LoaderManager.LoaderCallBack<Cursor>' 를 인터페이스로 추가

2. Implements 해야할 3개 함수 구현

3. 주요 구현부

. 로더 초기화 - static function 이므로 getLoaderManager() 만 호출 하면 된다.

getLoaderManager().initLoader(0, null, this);


. onCreateLoader() - 가져올(접근할) 데이터를 지정

. onLoaderFinished() - 로드가 완료되면 adapter 에 지정하거나 커서를 가져올 수 있게 된다.


<activity_main.xml>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">

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


---

<MainActivity.java>

import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> {

SimpleCursorAdapter mAdapter;

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


String[] columns = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
int[] ids = new int[] {android.R.id.text1};
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, columns, ids, 0);

setListAdapter(mAdapter);

getLoaderManager().initLoader(0, null, this);
}

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {

CursorLoader cursorLoader = new CursorLoader(MainActivity.this, ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

return cursorLoader;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}



---

HttpClient 가 android 6.0 에서 삭제 되었다.


build.gradle 에 


android {
    useLibrary
'org.apache.http.legacy'
}


를 추가 한뒤에 사용하던지 - deprecated 된 상태로 나온다. - 가로줄 쳐짐.


HttpURLConnection 을 대신 사용 하도록 한다.

URL url = new URL("http://some-server");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");

// read the response
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);




안드로이드 시스템 이미지 및 아이콘(기본아이콘) 정보 확인 가능한 사이트


:안드로이드 자체에서 제공하는 이미지(아이콘포함)에 대한 정보를 확인 할 수 있는 사이트


<xml 에서 접근시>

android:icon="@android:drawable/ic_menu_edit"


<code 로 접근시>

android.R.drawable.ic_menu_edit       



1. Unity 용 플러그인 다운로드

https://github.com/googleads/googleads-mobile-plugins/releases


2. Unity Project 창에 'GoogleMobileAds' 폴더와 'Plugings' 폴더가 생성됨


3. 작업하고자 하는 Scene 에서 빈 게임오브젝트를 하나 생성 - ex) AdmobManager


4. 해당 오브젝트에 스크립트를 추가


-----------------------------------------------

[AdmobLoad.cs]

using UnityEngine;

using System.Collections;


using GoogleMobileAds.Api;  // 추가


public class AdmobLoad : MonoBehaviour {


    BannerView bannerView;

    InterstitialAd interstitial;


// Use this for initialization

void Start () {

        bannerView = new BannerView("ca-app-pub-xxxxxxxxxxxxxxxxx (각자의 광고 ID)", AdSize.Banner, AdPosition.Bottom);

        AdRequest adRequest = new AdRequest.Builder().Build();

        bannerView.LoadAd(adRequest); // 배너광고

        interstitial.LoadAd(adRequest); // 전면광고

}

// Update is called once per frame

    //void Update () {

        

    //}


    public void ShowInterstitialAd() // 전면광고 호출 함수

    {

        if(interstitial.IsLoaded() == true)

        {

            interstitial.Show();

        }

    }

}


-----------------------------------------------

unity에서 git, svn 등 형상관리 툴로 관리 해야 할 폴더


- Assets

- ProjectSettings


만 관리 하면 됨.



환경 : Unity 5.0.0f4 -

유니티에서 안드로이드용 어플리케이션을 만든 뒤 종료처리를 위해 


if(Input.GetKeyDown(KeyCode.Escape))

{

Application.Quit();

}


위 코드를 수행할 경우 종료된뒤, 앱을 재실행 하는 경우 실행이 되지 않고 폰이 멈추는 현상이 있었다.


종료시 로그를 자세히 확인해 본 결과 아래와 같은 오류 메시지가 출력됨을 확인 할 수 있엇다.


RenderTexture warning: Destroying active render texture. Switching to main context.


유니티-안드로이드 종료 처리 및 위 로그 메시지를 가지고 구글링을 해보니 여러가지 방법들이 검색이 되어졌다. 


(*검색해본 결과들...)

- 안드로이드의 유니티 플레이어의 액티비티를 생성하여 받아온뒤 'finish()'

- 유니티 버전 패치

- 기타 스택오버플로우에서 검색된 방법들...


검색한 내용들을 적용해보아도 수정이 되지 않아 빌드 옵션을 바꾸어 보던중 'Other Settings' -> Multithreaded Rendering 옵션을 체크 해제한뒤 빌드&런 해보니 정상적으로 실행이 된뒤 종료를 해본결과 RenderTexture warning 이 보이지 않았으며, 재실행도 정상적으로 되었다.


아직 정확한 원인을 파악하진 못하였으나, 우선 문제는 해결된 셈이다.

원인 파악후 포스팅 수정 예정....

+ Recent posts