android 启动某个服务
在编写代码过程中往往需要单独启动某个服务,来辅助主线程的数据需要。
1、首先新建一个类,继承Server,重写onstart方法,在onStart中新建一个线程,在该线程中编写服务代码。
1 package com.yingjie.jzlfapp.server; 2 3 import com.yingjie.jzlfapp.model.net.PhoneMessage; 4 5 import android.app.Service; 6 import android.content.Intent; 7 import android.os.IBinder; 8 9 public class PhoneInfoService extends Service { 10 11 @Override 12 public int onStartCommand(Intent intent, int flags, int startId) { 13 new Thread(new Runnable() { 14 15 @Override 16 public void run() { 17 //具体实现服务的代码 18 new PhoneMessage(PhoneInfoService.this); 19 } 20 }).start(); 21 return super.onStartCommand(intent, flags, startId); 22 } 23 24 @Override 25 public IBinder onBind(Intent arg0) { 26 return null; 27 } 28 29 }
2、在清单文件中注册该Server
1 <service android:name="com.yingjie.jzlfapp.server.PhoneInfoService" > 2 <intent-filter> 3 <action android:name="com.yingjie.jzlfapp.server.PhoneInfoService" /> 4 5 <category android:name="android.intent.category.DEFAULT" /> 6 </intent-filter> 7 </service>
3、启动该服务
startService(new Intent("com.yingjie.jzlfapp.server.PhoneInfoService"));