google에서는 android support library사용을 추천한다. 이를 사용함으로써 많은 버전의 안드로이드 기기들이 app을 사용가능하게 되기 때문이다. 이는 file->project structure를 통해 나오는 관리창의 dependencies항목에서 추가 가능하다.
When you develop an app on a latest version of android like 5.x and you also want it to run on those devices which are running older versions of android like 3.2 e.t.c. you can’t do that until you add backward compatibility to your code.
To provide this backward compatibility android provides you the Android Support Library package. The Android Support Library package is a set of code libraries that provide backward-compatible versions of Android framework APIs as well as features that are only available through the library APIs. Each Support Library is backward-compatible to a specific Android API level.
Including the Support Libraries in your Android project is considered a best practice for application developers, depending on the range of platform versions your app is targeting and the APIs that it uses.
Support Library Features
The Android Support Library package contains several libraries that can be included in your application. Each of these libraries supports a specific range of Android platform versions and set of features.
In order to effectively use the libraries, it is important to consider that which API level you want to target as each library supports different API level.
Following is a brief description of android support libraries and API level they support.
Downloading the Support Libraries
Please note that before installing the support library packages you should be clear that what feature you want to use in your app.
The Android Support Library package is available through the Android SDK Manager.
Follow the following steps to download the support library package through the SDK Manager.
Start the android SDK Manager.
In the SDK Manager window, scroll to the end of the Packages list, find the Extras folder.
Select the Android Support Library item.
Click the Install packages button.
After downloading, the tool installs the Support Library files to your existing Android SDK directory. The library files are located in the following subdirectory of your SDK: /extras/android/support/ directory.
Choosing Support Libraries
Before adding a Support Library to your application, decide what features you want to include and the lowest Android versions you want to support.
Changes in Android build.gradle
If you are increasing the backward compatibility of your existing application to an earlier version of the Android API with the Support Library, make sure to update your application’s build.gradle. Specifically, you should update the compileSdkVersion element in the build.gradle to the new, lower version number, as shown below −
google에서는 android support library사용을 추천한다. 이를 사용함으로써 많은 버전의 안드로이드 기기들이 app을 사용가능하게 되기 때문이다. 이는 file->project structure를 통해 나오는 관리창의 dependencies항목에서 추가 가능하다.
When you develop an app on a latest version of android like 5.x and you also want it to run on those devices which are running older versions of android like 3.2 e.t.c. you can’t do that until you add backward compatibility to your code.
To provide this backward compatibility android provides you the Android Support Library package. The Android Support Library package is a set of code libraries that provide backward-compatible versions of Android framework APIs as well as features that are only available through the library APIs. Each Support Library is backward-compatible to a specific Android API level.
Including the Support Libraries in your Android project is considered a best practice for application developers, depending on the range of platform versions your app is targeting and the APIs that it uses.
Support Library Features
The Android Support Library package contains several libraries that can be included in your application. Each of these libraries supports a specific range of Android platform versions and set of features.
In order to effectively use the libraries, it is important to consider that which API level you want to target as each library supports different API level.
Following is a brief description of android support libraries and API level they support.
Downloading the Support Libraries
Please note that before installing the support library packages you should be clear that what feature you want to use in your app.
The Android Support Library package is available through the Android SDK Manager.
Follow the following steps to download the support library package through the SDK Manager.
Start the android SDK Manager.
In the SDK Manager window, scroll to the end of the Packages list, find the Extras folder.
Select the Android Support Library item.
Click the Install packages button.
After downloading, the tool installs the Support Library files to your existing Android SDK directory. The library files are located in the following subdirectory of your SDK: /extras/android/support/ directory.
Choosing Support Libraries
Before adding a Support Library to your application, decide what features you want to include and the lowest Android versions you want to support.
Changes in Android build.gradle
If you are increasing the backward compatibility of your existing application to an earlier version of the Android API with the Support Library, make sure to update your application’s build.gradle. Specifically, you should update the compileSdkVersion element in the build.gradle to the new, lower version number, as shown below −
log화일 작성을 위해서는 import android.util.Log를 한후 사용한다. 개발시 효율적인 log 관리를 위해 private static final TAG = “테그이름” 을 만들고 Log 작성시 이 tag를 이용한다. https://youtu.be/9LbETUPM_sY?t=35
@+id/이름 , @string/변수이름 등과 같은 레퍼런스에 ctrl를 누를 상태로 마우스를 가져다 대면 본래 정의 되어있는 코드로 이동가능하능한 링크가 만들어 진다.
activity의 onCreate() 내에서 setContentView(R.layout.레이아웃이름) 을 통해 layout을 load 한다.
android studio ui 창을 이용하지 않고 code로 element를 loadj하는 경우 import android.widget.RelativeLayout, import android.widget.Button 과 같이 먼저 import해야 한다. 그리고 obj를 생성하고 레이아웃obj.addView()를 이용해서 element를 덧붙일수 있다. 그리고 setContentView(레이아웃obj) 를 통해 비쥬얼라이즈 한다.
하고 activity는 implements GestureDetector.onGestureListener, GestureDetector.onDoubleTapListener. alt+ins 를 통해 ilstener의 method를 override하고 각각의 method내에서의 작업 마지막에는 return true를 명시해 이벤트가 잘 처리되었음을 알린다.
여러개의 activity에서 사용되는 공통된 부분은 fragment를 만들어 공유사용하는 방법이 있다.
adding image in project
fragment를 사용하는 경우 fragment xml 화일이 있어야 한다. 즉 하나의 fragment는 하나의 xml화일로 존재한다는 의미이며 이렇게 되어야 여러 activity에서 사용될수 있다.
public static class ExampleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.example_fragment, container, false); } }
activity xml에 fragment xml 추가 하는 방법
fragment간 직접 data를 주고 받을수는 없고 activity를 거쳐서 data를 주고 받을수 있다.
fragment의 onAttach() – 이함수는 fragement가 activity에 연결될때 호출된다. onAttach() 함수 안에서 변수로 받은 중앙 activity의 obj를 fragment 내의 한 property에 할당하고 activity obj에 있는 interface method에 data를 전달한다. 그리고 activity에 정의된 interface method내에서 data를 처리하고 그것을 activity가 다른 fragment에 전달한다.
Intent intent = new Intent(); intent.setAction("com.example.broadcast.MY_NOTIFICATION"); intent.putExtra("data","Notice me senpai!"); sendBroadcast(intent);
public class HelloIntentService extends IntentService {
/** * A constructor is required, and must call the super <code><a href="/reference/android/app/IntentService.html#IntentService(java.lang.String)">IntentService(String)</a></code> * constructor with a name for the worker thread. */ public HelloIntentService() { super("HelloIntentService"); }
/** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, IntentService * stops the service, as appropriate. */ @Override protected void onHandleIntent(Intent intent) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. try { Thread.sleep(5000); } catch (InterruptedException e) { // Restore interrupt status. Thread.currentThread().interrupt(); } } }
The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to an Adapter, which retrieves data from an external source and creates a View that represents each data entry.
Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and building views for an AdapterView ( i.e. ListView or GridView). The common adapters are ArrayAdapter,Base Adapter,CursorAdapter, SimpleCursorAdapter,SpinnerAdapter and WrapperListAdapter.
listViewObj.setClickable(true);
listViewObj.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = listViewObj.getItemAtPosition(position);
/* write you handling code like...
String st = "sdcard/";
File f = new File(st+o.toString());
// do whatever u want to do with 'f' File object
*/
}
});
또는
listViewObj.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text or do whatever you need.
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
model 역활을 하는 java 화일이 필요하다 그 화일안에는 we define the SQLite table name, column names and create table SQL query along with getter / setter methods. ( 기본으로 constructor, onCreate, onUpgrade함수를 가지고 있어야 한다. )
또한 perform the CRUD operations 하기 위해서 SQLiteOpenHelper.를 extends하는 java 화일이 필요하다.
import android.content.pm.PackageManager;
PackageManager pm = context.getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
}
take photo and get result
public final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1034;
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
...
...
// Start the image capture intent to take photo
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// by this point we have the camera photo on disk
Bitmap takenImage = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
// RESIZE BITMAP, see section below
// Load the taken image into a preview
ImageView ivPreview = (ImageView) findViewById(R.id.ivPreview);
ivPreview.setImageBitmap(takenImage);
} else { // Result was a failure
Toast.makeText(this, "Picture wasn't taken!", Toast.LENGTH_SHORT).show();
}
}
}
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key); int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);
alt+enter
필요한 library import 하기
asynctask
다른 thread상에서 작업을 수행해야 하는 경우에 사용한다. 단 지정된 작업이 한번 수행되면 끝나게 된다.
handlerthread
다른 thread상에서 작업을 수행하는데 asynctask와는 다르게 여러개 일련의 작업을 수행할수 있다. handler, looper, message 등을 이용한다.
작업을 지연시키는 방법
Handler.sendMessageDelayed()
Hanlder.postDelayed()를 이용하는 방법
AlarmManager를 이용하는 방법 특정시간후에나 특정되지않은 어느 정도 시간후에 작업수행한다.
PendingIntent를 이용 추후에 PendingIntent의 send()를 호출하여 원하는 때에 작업 수행한다.
JobScheduler, JobServices를 이용 특정 조건이 만족 되는 때에 작업 수행하게 한다.
Sync Adapter를 이용하는 방법이 있다. 이는 반복적인 네트워크 작업에 적합하다.
services
IntentService : IntentService를 extends하는 service class를 만들고 이를 manifest file에 등록한다. 다른 activity나 fragment에서 액티버티obj.startService(인텐트obj) 를 통해 service작업( background작업 )을 시작하게 한다.
Service : activity나 다른 service와 같은 component에 bind되어서 activity, 다른 service에서 service내의 함수에 접근 가능하며 Bound Service라고 불린다. 구현방법에 따라 Binder를 이용한 방법, handler와 messenger를 이용한 방법, AIDL를 이용한 방법이 있다.
service자체에서만 작업흐름을 제어가능하고 즉 service를 시작한 activity, fragment에서는 제어하지 못하는 경우. non-sticky service라고 불린다.
android animation
ObjectAnimator ( property animator라고도 불린다 )를 이용한 방법
때때로 시작점과 종료점을 구하는데 도움을 주는 TypeEvaluator를 덧붙여 사용하기도 한다.