본문 바로가기
Programming/Android

안드로이드 서비스 실행 (다른 App 구동할 때)

  • 사용자가 다른 앱들을 사용할 때 application의 일부 기능을 백그라운드에서 유지 해야 하는경우
  • 백그라운드 작업을 할 수 있는 Service class 생성 main application에서 서비스를 시작한다.

@Override

    public void onCreate(Bundle savedInstanceState) {

        Intent theIntent = new Intent(this, GpsService.class);

        Button startButton = (Button) findViewById(R.id.startButton);

        startButton.setOnClickListener(new OnClickListener() {

            @Override

            public void onClick(View v) {

                startService(theIntent);

                Toast.makeText(Main.this, "Starting", Toast.LENGTH_LONG).show();

            }

        });

        Button stopButton = (Button) findViewById(R.id.stopButton);

        stopButton.setOnClickListener(new OnClickListener() {

            @Override

            public void onClick(View v) {

                stopService(theIntent);

                Toast.makeText(Main.this, "Stopped", Toast.LENGTH_LONG).show();

            }

        });

}

 

public class TrackService extends Service {

    private LocationManager mgr;

    private String preferredProvider;

 

    @Override

    public IBinder onBind(Intent intent) {

        return null;

    }

 

    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        initGPS(); // sets up the LocationManager mgr

        if (preferredProvider != null) {

            mgr.requestLocationUpdates(preferredProvider, MIN_SECONDS * 1000,

                    MIN_METRES, this);

            return START_STICKY;

        }

        return START_NOT_STICKY;

    }

 

    @Override

    public boolean onUnbind(Intent intent) {

        mgr.removeUpdates(this);

        return super.onUnbind(intent);

    }

}

 

 

'Programming > Android' 카테고리의 다른 글

EventBus for Android  (0) 2014.07.15
네이버 맵 안드로이드에서 사용하기  (0) 2014.06.28
Custom Font 사용  (0) 2014.04.21
[android] Custom MediaPlayerControl 처리 예  (0) 2014.02.18
파일명 소문자로 일괄 변경 배치  (0) 2013.12.17