본문 바로가기
모바일개발(Mobile Dev)/안드로이드개발(Android)

service template in android

by 테크한스 2017. 7. 27.
반응형
public class MainActivity extends Activity
{
private CustomService mService = null;

private boolean mIsBound;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    startService(new Intent(this.getBaseContext(), CustomService.class));
    doBindService();
}


private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder)
    {
        mService = ((CustomService.LocalBinder)iBinder).getInstance();
        mService.setHandler(yourHandler);
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName)
    {
        mService = null;
    }
};

private void doBindService()
{
    // Establish a connection with the service.  We use an explicit
    // class name because we want a specific service implementation that
    // we know will be running in our own process (and thus won't be
    // supporting component replacement by other applications).
    bindService(new Intent(this,
            CustomService.class), mConnection, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

private void doUnbindService()
{
    if (mIsBound)
    {
        // Detach our existing connection.
        unbindService(mConnection);
        mIsBound = false;
    }
}

@Override
protected void onDestroy()
{
    super.onDestroy();
    doUnbindService();
}
public class CustomService extends Service
{
private final IBinder mIBinder = new LocalBinder();

private Handler mHandler = null;

@Override
public void onCreate()
{
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flag, int startId)
{
    return START_STICKY;
}

@Override
public void onDestroy()
{
    if(mHandler != null)
    {
        mHandler = null;
    }
}

@Override
public IBinder onBind(Intent intent)
{
    return mIBinder;
}

public class LocalBinder extends Binder
{
    public CustomService getInstance()
    {
        return CustomService.this;
    }
}

public void setHandler(Handler handler)
{ 
   mHandler = handler;
}

}






import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

MyService ms; // 서비스 객체
boolean isService = false; // 서비스 중인 확인용

ServiceConnection conn = new ServiceConnection() {
public void onServiceConnected(ComponentName name,
IBinder service) {
// 서비스와 연결되었을 때 호출되는 메서드
// 서비스 객체를 전역변수로 저장
MyService.MyBinder mb = (MyService.MyBinder) service;
ms = mb.getService(); // 서비스가 제공하는 메소드 호출하여

System.out.println("[DEBUG][MainActivity][onServiceConnected]MyService= "+ms);
// 서비스쪽 객체를 전달받을수 있슴
isService = true;
}
public void onServiceDisconnected(ComponentName name) {
// 서비스와 연결이 끊겼을 때 호출되는 메서드
isService = false;
}
};





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


Button b1 = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
Button b3 = (Button) findViewById(R.id.button3);

b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { // 서비스 시작
Intent intent = new Intent(
MainActivity.this, // 현재 화면
MyService.class); // 다음넘어갈 컴퍼넌트

bindService(intent, // intent 객체
conn, // 서비스와 연결에 대한 정의
Context.BIND_AUTO_CREATE);
System.out.println("[DEBUG][START] bindService ");
}
});
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { // 서비스 종료

unbindService(conn); // 서비스 종료
System.out.println("[DEBUG][STOP] unbindService ");
}

});
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {//서비스데이터확인
if (!isService) {
Toast.makeText(getApplicationContext(),
"서비스중이 아닙니다, 데이터받을수 없음",
Toast.LENGTH_LONG).show();
return;
}
int num = ms.getRan();//서비스쪽 메소드로 값 전달 받아 호출
Toast.makeText(getApplicationContext(),
"받아온 데이터 : " + num,
Toast.LENGTH_LONG).show();
}
});


}
}






import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import java.util.Random;



public class MyService extends Service {
// 외부로 데이터를 전달하려면 바인더 사용

// Binder 객체는 IBinder 인터페이스 상속구현 객체입니다
//public class Binder extends Object implements IBinder

IBinder mBinder = new MyBinder();

class MyBinder extends Binder {
MyService getService() { // 서비스 객체를 리턴
return MyService.this;
}
}

@Override
public IBinder onBind(Intent intent) {
// 액티비티에서 bindService() 를 실행하면 호출됨
// 리턴한 IBinder 객체는 서비스와 클라이언트 사이의 인터페이스 정의한다
return mBinder; // 서비스 객체를 리턴
}

int getRan() { // 임의 랜덤값을 리턴하는 메서드
return new Random().nextInt();
}
@Override
public void onCreate() {
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}


https://stackoverflow.com/questions/22573301/how-to-pass-a-handler-from-activity-to-service

반응형