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

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

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;@Overridepublic 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();}@Overridepublic IBinder onBind(Intent intent) {Toast.makeText(this, "MusicSevice onBind()",Toast.LENGTH_SHORT).show();Log.e(TAG, "MusicSerice onBind()");mPlayer.start();return null;}@Overridepublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubsuper.onStart(intent, startId);Toast.makeText(this, "MusicSevice onStart()", Toast.LENGTH_SHORT).show();Log.e(TAG, "MusicSerice onStart()");mPlayer.start();super.onStart(intent, startId);}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();Toast.makeText(this, "MusicSevice onDestroy()", Toast.LENGTH_SHORT).show();Log.e(TAG, "MusicSerice onDestroy()");mPlayer.stop();super.onDestroy();}//其它对象通过unbindService方法通知该Service时该方法被调用@Overridepublic 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交流学习

更多相关文章

  1. Android多种方法获取系统时间
  2. Android(安卓)-- TypedArray
  3. Android常用的api调用接口
  4. android工程下轻松运行java main程序
  5. 基于TCP/IP协议的Java服务端与Android客户端的Socket通信及数据
  6. Android使用系统方法实现分享到QQ和微信!
  7. Android的线程使用来更新UI----Thread、Handler、Looper、TimerT
  8. 浅谈Java中Collections.sort对List排序的两种方法
  9. Python list sort方法的具体使用

随机推荐

  1. Android使用ListView使用
  2. [连载 1/15] Android(安卓)从入门到精通E
  3. Android单个进程内存分配策略
  4. [Android(安卓)Pro] android 混淆文件pro
  5. Android(安卓)Studio、Android(安卓)SDK
  6. LinearLayout布局之weight
  7. android 拍照+从手机相册选择返回图片到i
  8. Android(安卓)生成keystore(user & debug
  9. android:visibility="gone"
  10. android studio中运行main方法报错问题解