关闭创建它的Activity后,服务会停止吗?

时间:2014-06-26 06:12:14

标签: android android-service

我创建了Service,并在Activity点击时开始使用Button,但Service在关闭Activity后停止。那么我该如何继续运行Service而不停止?

MainActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }

public void startService(View v){
    Intent i = new Intent(this, NotStickyService.class);
    startService(i);
}


 public void stopService(View v){
    Intent i = new Intent(this, NotStickyService.class);
    stopService(i);
}

Service.java

public class NotStickyService extends Service{

    MediaPlayer mp;


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

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        showToast("onStart");
        mp = new MediaPlayer();     
    AssetFileDescriptor descriptor;
    descriptor = getAssets().openFd("msg.mp3");
        mp.setDataSource(descriptor.getFileDescriptor(),     
        descriptor.getStartOffset(),descriptor.getLength());                                                   
            descriptor.close();
            mp.prepare();
            mp.start();
        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();    
        showToast("onDestroy");        
    }

    private void showToast(String message){
        Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
        toast.show();
    }
}

0 个答案:

没有答案