developer tip

Android 서비스는 항상 실행되어야 함 (일시 중지 또는 중지하지 않음)

optionbox 2020. 11. 15. 11:14
반응형

Android 서비스는 항상 실행되어야 함 (일시 중지 또는 중지하지 않음)


서비스를 생성했으며 전화기가 다시 시작되거나 강제 종료 될 때까지 항상이 서비스를 실행하고 싶습니다. 서비스는 백그라운드에서 실행되어야합니다.

생성 된 서비스 및 시작 서비스의 샘플 코드 :

서비스 시작 :

Intent service = new Intent(getApplicationContext(), MyService.class);
getApplicationContext().startService(service);

서비스:

public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful
        HFLAG = true;
        //smsHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 1000);
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO for communication return IBinder implementation
        return null;
    }
}

매니페스트 선언 :

<service
    android:name=".MyService"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
</service>

이 서비스는 응용 프로그램이 일시 중지 될 때와 다른 어떤 것이 든 항상 실행할 수 있습니까? 잠시 후 내 응용 프로그램이 일시 중지되고 서비스도 일시 중지되거나 중지됩니다. 이 서비스를 어떻게 백그라운드에서 항상 실행할 수 있습니까?


"이 서비스는 응용 프로그램이 일시 중지 될 때와 같이 항상 실행할 수 있습니까?"

예.

  1. 서비스 onStartCommand 메소드에서 START_STICKY를 반환합니다.

    public int onStartCommand(Intent intent, int flags, int startId) {
            return START_STICKY;
    }
    
  2. 바인딩 된 클라이언트 수에 관계없이 항상 활성 상태로 유지되도록 startService (MyService)를 사용하여 백그라운드에서 서비스를 시작합니다.

    Intent intent = new Intent(this, PowerMeterService.class);
    startService(intent);
    
  3. 바인더를 만듭니다.

    public class MyBinder extends Binder {
            public MyService getService() {
                    return MyService.this;
            }
    }
    
  4. 서비스 연결을 정의하십시오.

    private ServiceConnection m_serviceConnection = new ServiceConnection() {
            public void onServiceConnected(ComponentName className, IBinder service) {
                    m_service = ((MyService.MyBinder)service).getService();
            }
    
            public void onServiceDisconnected(ComponentName className) {
                    m_service = null;
            }
    };
    
  5. bindService를 사용하여 서비스에 바인딩하십시오.

            Intent intent = new Intent(this, MyService.class);
            bindService(intent, m_serviceConnection, BIND_AUTO_CREATE);
    
  6. 서비스의 경우 해당 활동이 종료되면 알림이 시작되도록 할 수 있습니다.

    private void addNotification() {
            // create the notification
            Notification.Builder m_notificationBuilder = new Notification.Builder(this)
                    .setContentTitle(getText(R.string.service_name))
                    .setContentText(getResources().getText(R.string.service_status_monitor))
                    .setSmallIcon(R.drawable.notification_small_icon);
    
            // create the pending intent and add to the notification
            Intent intent = new Intent(this, MyService.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
            m_notificationBuilder.setContentIntent(pendingIntent);
    
            // send the notification
            m_notificationManager.notify(NOTIFICATION_ID, m_notificationBuilder.build());
    }
    
  7. 단일 최상위 모드에서 활동을 시작하려면 매니페스트를 수정해야합니다.

              android:launchMode="singleTop"
    
  8. 시스템에 리소스가 필요하고 서비스가 매우 활성화되지 않은 경우 종료 될 수 있습니다. 이것이 허용되지 않는 경우 startForeground를 사용하여 서비스를 포 그라운드로 가져옵니다.

            startForeground(NOTIFICATION_ID, m_notificationBuilder.build());
    

자체 프로세스에서 서비스를 시작하려면 xml 선언에 다음을 지정해야합니다.

<service
  android:name="WordService"
  android:process=":my_process" 
  android:icon="@drawable/icon"
  android:label="@string/service_name"
  >
</service> 

여기에서 나에게 정말 유용한 좋은 튜토리얼을 찾을 수 있습니다.

http://www.vogella.com/articles/AndroidServices/article.html

도움이 되었기를 바랍니다


간단한 해결책은 시스템이 중지 할 때 서비스를 다시 시작하는 것입니다.

이 방법의 매우 간단한 구현을 발견했습니다.

Android 서비스를 멈출 수 없게 만드는 방법


startForeground서비스를 구현할 수 있으며 서비스가 종료 되더라도 START_STICKYon 을 사용하여 다시 시작할 수 있습니다 startCommand(). 이것이 올바른 구현인지 확실하지 않습니다.


이미 서비스가 있고 항상 작동하도록하려면 다음 두 가지를 추가해야합니다.

  1. 서비스 자체에서 :

    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    
  2. 매니페스트에서 :

    android:launchMode="singleTop"
    

서비스에서 필요하지 않으면 bind를 추가 할 필요가 없습니다.


나는 Service항상 달리기 를 유지하는 간단하고 명확한 방법을 찾았다 .

이 사람은 그것을 아주 명확하게 설명했고 좋은 알고리즘을 사용했습니다. 그의 접근 방식은 서비스가 종료 되려고 할 때 브로드 캐스트를 보낸 다음이를 사용하여 서비스를 다시 시작하는 것입니다.

당신은 그것을 확인해야합니다 : http://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android


이것을 매니페스트에 추가하십시오.

      <service
        android:name=".YourServiceName"
        android:enabled="true"
        android:exported="false" />

서비스 클래스를 추가하십시오.

public class YourServiceName extends Service {


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

      // Timer task makes your service will repeat after every 20 Sec.
       TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                       // Add your code here.

                     }

               });
            }
        };
  //Starts after 20 sec and will repeat on every 20 sec of time interval.
        timer.schedule(doAsynchronousTask, 20000,20000);  // 20 sec timer 
                              (enter your own time)
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful

      return START_STICKY;
    }

}

I had overcome this issue, and my sample code is as follows.

Add the below line in your Main Activity, here BackGroundClass is the service class.You can create this class in New -> JavaClass (In this class, add the process (tasks) in which you needs to occur at background). For Convenience, first denote them with notification ringtone as background process.

 startService(new Intent(this, BackGroundClass .class));

In the BackGroundClass, just include my codings and you may see the result.

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;

public class BackgroundService  extends Service {
    private MediaPlayer player;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
     player = MediaPlayer.create(this,Settings.System.DEFAULT_RINGTONE_URI);
        player.setLooping(true);
         player.start();
        return START_STICKY;
    }
 @Override
    public void onDestroy() {
        super.onDestroy();
         player.stop();
    }
}

And in AndroidManifest.xml, try to add this.

<service android:name=".BackgroundService"/>

Run the program, just open the application, you may find the notification alert at the background. Even, you may exit the application but still you might have hear the ringtone alert unless and until if you switched off the application or Uninstall the application. This denotes that the notification alert is at the background process. Like this you may add some process for background.

Kind Attention: Please, Don't verify with TOAST as it will run only once even though it was at background process.

Hope it will helps...!!


You don't require broadcast receiver. If one would take some pain copy one of the api(serviceconnection) from above example by Stephen Donecker and paste it in google you would get this, https://www.concretepage.com/android/android-local-bound-service-example-with-binder-and-serviceconnection

참고URL : https://stackoverflow.com/questions/15758980/android-service-needs-to-run-always-never-pause-or-stop

반응형