Service和act一样,表示可执行程序,单Service是不直接与用户进行交互的,它是一种后台运行组件,如后台数据计算,后台播放音乐等。
建立Service有两种方法:
一:startService()和stopService()
1
定义Service类:
即在activity通目录下建立一个Service.java文件:该文件代码如下:
package com.example.survice8;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class Service1 extends Service {
@Override
public void onCreate(){
// TODO Auto-generated method stub
super.onCreate();
System.out.println("onCreate()");
//player=MediaPlayer.create(this,R.drawable.aa);
}
@Override
public int onStartCommand(Intent intent,int flags,int startId){
// TODO Auto-generated method stub
System.out.println("onStartCommand()");
return super.onStartCommand(intent,flags,startId);
}
@Override
public void onDestroy(){
// TODO Auto-generated method stub
System.out.println("onDestroy()");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
2:在AndroidManifest.xml下配置Service,与act类似位于app中间。
代码:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".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:name="Service1"></service>
</application>
3:
在act中绑定按钮,按下按钮后执行startService和stopService方法,这两个方法是需要自己生命的,利用Intent。
代码如下:
package com.example.survice8;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View V){
System.out.println("11111");
startService();
}
});
button2.setOnClickListener(new OnClickListener(){
public void onClick(View V){
System.out.println("22222");
stopService();
}
});
}
protected void stopService() {
// TODO Auto-generated method stub
Intent intent =new Intent(this,Service1.class);
stopService(intent);
}
protected void startService() {
// TODO Auto-generated method stub
Intent intent =new Intent(this,Service1.class);
startService(intent);
}
}
二:bindService和unbindService