본문 바로가기

Android

Sevice 구현 예제


위와 같은 디자인으로 다음과 같은 예제 소스를 입력하여 Service 기능을 확인할 수 있다. java class 아래와 같이 두개로 만든다.


package org.techtown.myservice16;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

EditText editText;

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

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

Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = editText.getText().toString();

Intent intent = new Intent(getApplicationContext(), MyService.class);
intent.putExtra("command", "show");
intent.putExtra("name", name);
startService(intent);

}
});

Intent passedIntent = getIntent();
processCommand(passedIntent);

}

@Override
protected void onNewIntent(Intent intent) {
processCommand(intent);

super.onNewIntent(intent);
}

private void processCommand(Intent intent){
if (intent != null){
String command = intent.getStringExtra("command");
String name = intent.getStringExtra("name");

Toast.makeText(this, "서비스로부터 전달받은 데이터 : " + command + ", " + name, Toast.LENGTH_LONG).show();
}
}
}
package org.techtown.myservice16;

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() {
super.onCreate();

Log.d(TAG, "onCreate() 호출됨.");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand() 호출됨.");

if(intent == null){
return Service.START_STICKY;
} else {
processCommand(intent);
}

return super.onStartCommand(intent, flags, startId);
}

private void processCommand(Intent intent){
String command = intent.getStringExtra("command");
String name = intent.getStringExtra("name");

Log.d(TAG, "전달받은 데이터 : " + command + "," + name);

try {
Thread.sleep(5000);
} catch (Exception e){

}

Intent showIntent = new Intent(getApplicationContext(), MainActivity.class);
showIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
Intent.FLAG_ACTIVITY_SINGLE_TOP|
Intent.FLAG_ACTIVITY_CLEAR_TOP);
showIntent.putExtra("command", "show");
showIntent.putExtra("name", name + "from service. ");
startActivity(showIntent);
}

@Override
public void onDestroy() {
super.onDestroy();

Log.d(TAG, "onStart() 호출됨.");
}

@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
}


'Android' 카테고리의 다른 글

Recycler View 예제  (0) 2017.09.15
안드로이드 Json 파싱  (0) 2017.09.13
Parcelable  (0) 2017.08.01
PDF 파일을 띄우는 Source  (0) 2017.07.26
Inflater  (0) 2017.07.25