第一步修改androidmanifest文件,添加service android name
<application> <service android:name=".MyService"/> </application>第二步新建一个Myservice类文件,内容如下:
package com.example.android;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
private boolean running=false;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate(){
super.onCreate();
running=true;
new Thread(){
public void run(){
super.run();
while(running){
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
}
// @Override
// public int onStartCommand(Intent intent,int flags,int startId) {
// super.onStartCommand(intent, flags, startId);
// return START_STICKY;
// }
@Override
public void onDestroy(){
super.onDestroy();
running=false;
}
}
第三步启用service或关闭service(分2种方式一种local service即程序1启动或关闭自己的服务,而remote service是通过程序2启动或关闭程序1的服务)
local service:
启用service:startService(new Intent(this, MyService.class));
关闭service:stopService(new Intent(this, MyService.class));
remote service:
启用程序1的service
Intent i=new Intent();
i.setComponent(new ComponentName("被启动的程序包名","被启动的程序service类名");
startService(i);
Intent i=new Intent();
i.setComponent(new ComponentName("被启动的程序包名","被启动的程序service类名");
stopService(i);
参考http://www.cnblogs.com/wenjiang/p/3231986.html