woong's

Android service Message 전송하기 본문

Develop/Android

Android service Message 전송하기

dlsdnd345 2016. 2. 14. 12:56
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Android service Message 전송하기


​안녕하세요. Android Service 를 사용하다 보면 , Activity 에서 Service 의 메서드를 호출 해야 하는 경우가 있습니다 .

이경우 Aidl 을 통해서 Activity 에서 Service 의 메서드를 호출 할 수 있습니다 .

Service 를 호출 하기 위해서는 Aidl 이라는 파일이 필요 합니다 .



제가 사용한 Aidl 파일 입니다.

Service 와 통신을 하기위해서는 Aidl 파일이 필요 합니다 .

여기서 사용하고자 한 sayHello 메서드는 Service 에 구현 됩니다.


1
2
3
4
5
package com.example.service;
 
interface IMessageService {
    String sayHello(String name);
}


제가 사용한 Service 입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.example.service;
 
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
 
public class TestService extends Service {
     
    @Override
    public IBinder onBind(Intent intent) {
        return serviceStub;
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("서비스 Start");
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("서비스 Finish");
    }
 
    public IMessageService.Stub serviceStub = new IMessageService.Stub() {
 
        @Override
        public String sayHello(String name) throws RemoteException {
            System.out.println("메세지 수신 : " + name);
            return "Hello " + name;
        }
        
    };
    
}
 

 

 

​위 코드를 보시면 하단의 serviceStub 를 보시면 sayHello 가 구현 되어 있는 것을 볼 수 있습니다 . 

Aidl 을 통해서 틀을 갖추고 Service 에 구현하여 Activity에서 위 구현 코드를 호출하게 됩니다.



 

​Activity 에서 Service 를 호출 하는 부분 입니다 . 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.example.servicetest;
 
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
 
import com.example.service.IMessageService;
import com.example.service.TestService;
 
public class MainActivity extends Activity {
 
    private Intent                     intent;
    private IMessageService            messageService;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Intent service = new Intent(MainActivity.this, TestService.class);
        startService(service);
    }
    
    public void startService(View view){
        // 명시적 등록
        intent = new Intent(MainActivity.this, TestService.class);
        //서비스 시작
        startService(intent);
        bindService(intent,conn, Context.BIND_AUTO_CREATE);
    }
    
    public void finishService(View view){
        //서비스 종료
        stopService(intent);
        unbindService(conn);
    }
    
    public void sendMessage(View view){
        try {
            messageService.sayHello("인웅");
            
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * Bind 되는 시점에 호출
     */
    private ServiceConnection conn = new ServiceConnection (){
        public void onServiceDisconnected(ComponentName name){}
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            messageService = IMessageService.Stub.asInterface(service);
        }
    };
    
}
 

 

 

​위 Activity 코드를 보면 service 를 등록 / 해제 하는 것을 볼 수 있습니다 . 

이외의 하나의 메서드가 더 있는데 최하단의 Connection 이 있습니다 .

이 Connection 을 통해서 Service 를 제어 할수 있는 IBinder 를 넘겨 받습니다 .

 IBinder 를 통해서 Service 의 메서드를 호출 할 수 있습니다 .


위 sendMessage  를 보면 sayHello 를 호출 하는 것을 볼 수 있습니다.


 

​이번에 작성한 포스트는 Activity 에서 Service 메서드를 호출 하는 형태입니다 . 

 

Service 에서 Activity를 호출하는 방법은 다음 포스트를 통해서 작성해 보도록 하겠습니다 .


첨부파일로 해당 프로젝트를 첨부 하였습니다 . 위 글로 이해가 안되신다면 한번 

깔아서 설치 해보고 코드를 보시는것도 좋을것 같습니다 .


Comments