Srevice在安卓中是一个不可见的在后台执行的进程,避免用户误关闭。因为Android在某些情况下会自动关闭非前台显示的Activity,所以如果要让一个功能在后台一直执行,不被Android系统关闭,比如说闹钟、后台播放音乐,就必须使用Service。
XML布局文件:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>
主activity.java
package com.example.music;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button start;
Button stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findView();
start.setOnClickListener(startlis);
stop.setOnClickListener(stoplis);
}
private OnClickListener startlis=new OnClickListener(){
@Override
public void onClick(View v){
startService(new Intent(MainActivity.this,Music.class));
}
};
private OnClickListener stoplis=new OnClickListener(){
@Override
public void onClick(View v){
stopService(new Intent(MainActivity.this,Music.class));
}
};
public void findView(){
start=(Button)findViewById(R.id.start);
stop=(Button)findViewById(R.id.stop);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Music.java
package com.example.music;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class Music extends Service {
private MediaPlayer mp;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(){
super.onCreate();
mp=MediaPlayer.create(this, R.raw.xrx);
}
@Override
public void onStart(Intent intent,int startId){
super.onStart(intent, startId);
mp.start();
}
@Override
public void onDestroy(){
super.onDestroy();
mp.stop();
}
}
androidManiFeat.java
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.music"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.music.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:enabled="true" android:name=".Music"></service>
</application>
</manifest>