原文地址:http://blog.csdn.net/jfcoer/archive/2010/06/27/5697494.aspx
第一步:
写一个Service,播放音乐:
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
boolean destoryIt = false;
@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");
//设定,要播放的mp3文件
player = MediaPlayer.create(this,R.raw.greenday);
player.setLooping(false); // Set looping
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
destoryIt = true;
player.stop();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
第二步:
写一个 BroadcastReceiver,用来开机时启动MyService:
public class MyStartupIntentReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.NotificationDemo.service.MyService");
context.startService(serviceIntent);
}
}
第三步:
编辑AndroidManifest.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.NotificationDemo"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<service android:name=".service.MyService">
<intent-filter>
<action
android:name="com.NotificationDemo.service.MyService" />
</intent-filter>
</service>
<receiver android:name=".boot.MyStartupIntentReceiver">
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
</manifest>
完成,启动avd测试吧。ok
留言列表