2

В активности вызываю сервис

PendingIntent pi;
            Intent intent;
            Intent intent_empty = new Intent();
            // Создаем PendingIntent
            pi = createPendingResult(1 ,intent_empty, 0);
            // Создаем Intent для вызова сервиса
            // и созданный PendingIntent
            intent = new Intent(this, VideoService.class).putExtra(PARAM_PINTENT, pi).putExtra(PARAM_FLAG, false);
            // стартуем сервис
            startService(intent);

Он не запускается. Вообще. Код сервиса:

public void onCreate() {
    super.onCreate();
    System.out.println("onStartCommand");
  }

  public int onStartCommand(Intent intent, int flags, int startId) {
    System.out.println("onStartCommand");

    mCamera = getCameraInstance();
    mPreview = new CameraPreview(this, mCamera);

    boolean flag = intent.getBooleanExtra(VideoR.PARAM_FLAG, false);
    PendingIntent pi = intent.getParcelableExtra(VideoR.PARAM_PINTENT);

    if (!flag) {
        startRecord(pi);
    }
    else {
        stopRecord(pi);
    }

    return super.onStartCommand(intent, flags, startId);
  }

  public void onDestroy() {
    super.onDestroy();
    Log.d(LOG_TAG, "onDestroy");
  }

  public IBinder onBind(Intent intent) {
    Log.d(LOG_TAG, "onBind");
    return null;
  }
3
  • откуда знаешь что не запускается?
    – Gorets
    28 янв 2013 в 15:29
  • Потому что System.out.println ничего не выводит. При нажатии кнопки также ничего не происходит.
    – FoX4
    28 янв 2013 в 15:33
  • мне кажется ты забыл его в манифесте объявить
    – dajver
    28 янв 2013 в 16:05

1 ответ 1

2

Держи готовый сервис.

 public class MyService extends Service {
            MediaPlayer player;

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

            @Override
            public void onCreate() {
                player = MediaPlayer.create(this, R.raw.bg);
                player.setLooping(true); // зацикливаем
            }

            @Override
            public void onDestroy() {
                Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
                player.stop();
            }

            @Override
            public void onStart(Intent intent, int startid) {
                Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
                player.start();
            }
    }

Далее нам нужно его зарегистрировать в AndroidManifest'e.xml как и активити, для того что бы Eclipse знал что этот класс можно запускать как сервис:

<service android:enabled="true" android:name=".MyService" />

А дальше мы запускаем наш сервис из активности:

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

Ну и в нужном месте мы его будем останавливать, например по нажатию кнопки:

stopService(new Intent(this, MyService.class));
1
  • Точно! Я забыл в манифесте объявить сервис. Спасибо огромное за ответ!
    – FoX4
    28 янв 2013 в 16:18

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.