개발모음집

[안드로이드 프로그래밍] Day09 본문

Android

[안드로이드 프로그래밍] Day09

void 2016. 6. 7. 13:16

서비스는 백그라운드에서 실행되는 애플리이션 구성 요소


서비스는 시스템이 종료되도록 하더라도 다시 실행된다.



MyService의 MainActivity.java

package org.androidtown.myservice;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

public void onButton1Clicked(View v) {
Intent intent = new Intent(getApplicationContext(), MyService.class);
intent.putExtra("command", "start");
startService(intent);
}
}

MyService의 MyService.java

package org.androidtown.myservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
private static final String TAG = "MyService";

public MyService() {
} // 서비스는 화면이 있는게 아니기때문에 토스트보다는 로그를 띄어주는게 더 좋다

@Override
public void onCreate() {
Log.d(TAG, "onCreate() 호출됨");
super.onCreate();
}

@Override
public void onDestroy() {
Log.d(TAG, "onDestroy() 호출됨");
super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand() 호출됨");
if(intent != null ) {
String command= intent.getStringExtra("command");
if (command != null) {
if (command.equals("start")) {
PrintThread thread = new PrintThread();
thread.start();
}
}
}
return super.onStartCommand(intent, flags, startId);
}

class PrintThread extends Thread {
public void run() {
for (int i = 0 ; i < 100; i++) {
Log.d(TAG, "#" + i + " 서비스에서 반복됨");
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}

//onStartCommand() 안에서 스레드를 만들 수 있다.


브로드캐스트 수신자


브로드캐스팅으로 던져지는 인텐트 중에서 내가 어떤 것을 받겠다고 등록해주는 것


단말에서 먼저 받고, 필요한 앱으로 던져준다.

시스템에서 이해하도록 던져주는 것이 인텐트

ex)

sms라고 문자가 들어가는  인텐트를 받고 싶다고 등록을 하면 브로드캐스트에서 인텐트를 받을 수 있다.

(파싱: 이해한다.)


브로드캐스트의 구분



일반 브로드캐스팅: 동시에

순차 브로드캐스팅 한 번씩


MySMSReceiver의 AndroidManifest.java

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.androidtown.mysmsrceiver">

<user-permission android:name="android.permission.RECEIVE_SMS"></user-permission>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

<receiver
android:name=".MySMSReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
</manifest>
<!--
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
//intent-filter로 내가 받고 싶은 인텐트를 거르겠다.

<user-permission android:name="android.permission.RECEIVE_SMS"></user-permission> // SMS는 권한이 필요

-->


MySMSReceiver의 MySMSReceiver.java 파일

package org.androidtown.mysmsrceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class MySMSReceiver extends BroadcastReceiver {
private static final String TAG = "MySMSReceiver";

public MySMSReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) { // onReceive 인탠트를 받는 메소드
Log.d(TAG, "onReceive() 호출됨");
Intent myIntent = new Intent (context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP); // flag: 옵션정보, NEW_TASK: 새로운창띄우기, 기존에 띄어진 상태에선 FLAG_ACTIVITY_SINGLE_TOP
context.startActivity(myIntent);
}
}

// 서비스나 브로드캐스트 수신자는 액티비티가 없어도 실행한다.


values -  layout.land로 폴더를 지정하여 설정하면 가로화면을 지정할 수 있다.



리소스: res 폴더아래있는 파일


메니페스트에서 지정한 앱의 이름은

res.values.string.xml에서 

<resources>
<string name="app_name">MyIntent</string>
</resources>

로 저장된 것을 확인할 수 있다.


<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

intent-filter 태그안에 action태그와 cartegory태그가 들어간 곳이 메인액티비티이다.

(메이액티비티 지정할 수 있는 방법)


* 처음 프로젝트 생성시 [/res]폴더와 [/assets]폴더가 따로 분리됨 (나중에 설명해줌)

* Toast 변경 가능( 하지만 대부분 변경하지 않는다.)



대화상자 만들기 예제



package com.example.tristan91.mydialog;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

public void onButton1Clicked(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("안내");
builder.setMessage("종료하시겠습니까?");
builder.setIcon(android.R.drawable.ic_dialog_alert); //android.R.drawable안드로이드에서 미리 설치해둔 아이콘들 ic = icon
builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(), "'예' 버튼이 눌림", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(), "'아니오' 버튼이 눌림", Toast.LENGTH_LONG).show();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}

}