package com.example.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class HelloService extends Service{
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
//服务启动时调用的方法
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i("HelloService", "I am is onCreate()");
}
//服务运行过程中使用的方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//如果service这里不创建一个新的线程,那么它将使用调用它的那个线程,如果是耗时的操作,那么将会导致阻塞
new Thread(new Runnable(){
@Override
public void run(){
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"-"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
//在服务类内部使用stopSelf()停止服务,在外部则通过stopService()
Log.i("HelloService", "I am is onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
//服务停止时调用的方法
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i("HelloService", "I am is onDestroy()");
}
}
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class HelloService extends Service{
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
//服务启动时调用的方法
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i("HelloService", "I am is onCreate()");
}
//服务运行过程中使用的方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//如果service这里不创建一个新的线程,那么它将使用调用它的那个线程,如果是耗时的操作,那么将会导致阻塞
new Thread(new Runnable(){
@Override
public void run(){
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"-"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
//在服务类内部使用stopSelf()停止服务,在外部则通过stopService()
Log.i("HelloService", "I am is onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
//服务停止时调用的方法
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.i("HelloService", "I am is onDestroy()");
}
}