android后台运行服务,加验证

在写服务的情况下,我们需要开机自启动服务。网上很多代码都有问题,以下是我亲自试验过可行的。

接下来创建一个服务此服务会自动播放歌曲,用来验证服务是否正确运行

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 musicServer extends  Service {
private static String TAG = "musicServer";
private MediaPlayer mPlayer;
@Override
public void onCreate() {
Toast.makeText(this, "MusicSevice onCreate()"
, Toast.LENGTH_SHORT).show();
Log.e(TAG, "MusicSerice onCreate()");
mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.musi);
//设置可以重复播放
mPlayer.setLooping(true);
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "MusicSevice onBind()"
,Toast.LENGTH_SHORT).show();
Log.e(TAG, "MusicSerice onBind()");
mPlayer.start();
return null;
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "MusicSevice onStart()"
, Toast.LENGTH_SHORT).show();
Log.e(TAG, "MusicSerice onStart()");
mPlayer.start();
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "MusicSevice onDestroy()"
, Toast.LENGTH_SHORT).show();
Log.e(TAG, "MusicSerice onDestroy()");
mPlayer.stop();
super.onDestroy();
}
//其它对象通过unbindService方法通知该Service时该方法被调用
@Override
public boolean onUnbind(Intent intent) {
Toast.makeText(this, "MusicSevice onUnbind()"
, Toast.LENGTH_SHORT).show();
Log.e(TAG, "MusicSerice onUnbind()");
mPlayer.stop();
return super.onUnbind(intent);
}
}

qq:847771093老A欢迎大家加我QQ交流学习

你可能感兴趣的:(android,service,开机启动)