2016-07-31 4 views
0

안드로이드 서비스에 대한 많은 예제와 튜토리얼은 bound services입니다.하지만 바인딩되지 않은 서비스를 만들고 바인딩을 전혀 처리하지 않으려면 어떻게해야합니까?Android에서 언 바운드 서비스는 어떻게 만듭니 까?

이 downvoting하기 전에 왜 answering your own questions is a good thing에 읽어주십시오 가능성 downvoters에

 

참고. 이 모든 서비스가 수행

public class RecordingService extends Service { 
    private int NOTIFICATION = 1; // Unique identifier for our notification 

    public static boolean isRunning = false; 
    public static RecordingService instance = null; 


    private NotificationManager notificationManager = null; 


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

    @Override 
    public void onCreate(){ 
     instance = this; 
     isRunning = true; 

     notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

     super.onCreate(); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId){ 
     // The PendingIntent to launch our activity if the user selects this notification 
     PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); 

     // Set the info for the views that show in the notification panel. 
     Notification notification = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.mipmap.ic_launcher)  // the status icon 
       .setTicker("Service running...")   // the status text 
       .setWhen(System.currentTimeMillis())  // the time stamp 
       .setContentTitle("My App")     // the label of the entry 
       .setContentText("Service running...")  // the content of the entry 
       .setContentIntent(contentIntent)   // the intent to send when the entry is clicked 
       .setOngoing(true)       // make persistent (disable swipe-away) 
       .build(); 

     // Start service in foreground mode 
     startForeground(NOTIFICATION, notification); 

     return START_STICKY; 
    } 


    @Override 
    public void onDestroy(){ 
     isRunning = false; 
     instance = null; 

     notificationManager.cancel(NOTIFICATION); // Remove notification 

     super.onDestroy(); 
    } 


    public void doSomething(){ 
     Toast.makeText(getApplicationContext(), "Doing stuff from service...", Toast.LENGTH_SHORT).show(); 
    } 

} 

은 다음과 같습니다

<application ...> 

    ...   

    <service 
     android:name=".RecordingService" 
     android:exported="false"> 

</application> 

그런 다음 우리가 실제 서비스 클래스를 만들 :

+0

당신은 분 이내에 자신의 게시물을 대답 했 ...!? – Shaishav

+0

@Shaishav 예 했어요. 사실 "Ask a question"페이지의 하단에있는 확인란을 사용하여 게시하기 전에 답변했습니다. Stackoverflow에서 간단한 언 바운드 서비스를 만드는 방법에 대한 명확하고 완전한 데모를 찾을 수 없으므로 지금 어떻게 해야할지를 알기 시작했습니다. [자신의 질문에 대한 답변을 보려면 여기를 클릭하십시오.] – BadCash

+0

차갑다. 정보 주셔서 감사합니다. – Shaishav

답변

1

할 첫번째 일은 <application> 태그 안에, 매니페스트에 서비스를 추가하는 것입니다 실행 중일 때 알림을 표시하고 doSomething() 메소드가 호출되면 토스트를 표시 할 수 있습니다.

알다시피이 인스턴스는 singleton으로 구현되어 자체 인스턴스를 추적하지만 서비스는 자연스럽게 싱글 톤이며 의도로 작성되기 때문에 일반적인 정적 싱글 톤 팩토리 메서드가 없습니다. 인스턴스는 외부에서 실행 중일 때 서비스에 "핸들"을 가져 오는 것이 유용합니다. 이 예에서

public void startOrStopService(){ 
    if(RecordingService.isRunning){ 
     // Stop service 
     Intent intent = new Intent(this, RecordingService.class); 
     stopService(intent); 
    } 
    else { 
     // Start service 
     Intent intent = new Intent(this, RecordingService.class); 
     startService(intent); 
    } 
} 

이 서비스가 시작되고 그것의 현재 상태에 따라 동일한 방법으로 중지 :

마지막으로, 우리는 시작 활동에서 서비스를 중지해야합니다.

우리는 또한 우리의 활동에서 doSomething() 메소드를 호출 할 수 있습니다 :

public void makeServiceDoSomething(){ 
    if(RecordingService.isRunning) 
     RecordingService.instance.doSomething(); 
}