为什么在应用程序进程被终止后重新启动服务

时间:2013-07-30 06:30:53

标签: android service

我有以下启动服务的代码:

package com.example.serviceapp;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
    private static final String TAG = "MyService";
    MediaPlayer player;

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

    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");

        player = MediaPlayer.create(this, R.raw.music);
        player.setLooping(false); // Set looping
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
        player.start();

        /*
         * START_STICKY: Constant to return from onStartCommand(Intent, int,
         * int): if this service's process is killed while it is started (after
         * returning from onStartCommand(Intent, int, int)), then leave it in
         * the started state but don't retain this delivered intent.
         */
        return START_STICKY;
    }

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

}

但是当应用程序进程被终止时,服务会停止并重新启动,为什么?

这是我开始/停止服务的方式:

public class MainActivity extends Activity {
    private static final String TAG = "ServicesDemo";
    Button buttonStart, buttonStop;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonStart = (Button) findViewById(R.id.buttonStart);
        buttonStop = (Button) findViewById(R.id.buttonStop);

        buttonStart.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: starting srvice");
                startService(new Intent(getApplicationContext(),
                        MyService.class));
            }
        });
        buttonStop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: stopping srvice");
                stopService(new Intent(getApplicationContext(), MyService.class));
            }
        });
    }

}

1 个答案:

答案 0 :(得分:0)

启动服务时使用START_STICKY标志。这意味着必须明确启动和停止服务。如果服务在两者之间被杀死,android会重启它。这使得确定除非您发送停止服务的意图,否则它将继续运行。

你可以设置标志START_NOT_STICKY,告诉android如果它被杀死,它将不会自动重启服务。