http://www.tutorialspoint.com/android/android_services.htm
1. 新建一个service文件:MyService.java
package com.example.helloworld;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
2. 在Manifest.xml中声明:
<service android:name=".MyService" />
3. 修改界面文件:增加2个buttong, 来启动和停止 service
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="68dp"
android:text="Start Service"
<span style="color:#ff0000;">android:onClick="startService" /></span>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:text="Stop Service"
<span style="color:#ff0000;">android:onClick="stopService"/></span>
4. 在界面xml中调用的两个函数:定义在MainActivity.java中
//Method to start the service
public void startService(View view) {
startService(new Intent(getBaseContext(), MyService.class));
}
public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
编译,运行。
多体会下面的切换过程: