上次我写过一个关于Android服务检测的,结果那段代码是错误的,根本不能实现,我现在重新发一段正确的。
这次我把检测写成一个服务(Service),使用时在Activity里面调用就行了。
import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.telephony.PhoneStateListener; import android.telephony.ServiceState; import android.telephony.TelephonyManager; public class GsmStateService extends Service { exPhoneStateListener psl=new exPhoneStateListener(); private int ib_state; @Override public void onCreate() { //取得电话服务 TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); //注册listener tm.listen(psl, PhoneStateListener.LISTEN_SERVICE_STATE); System.out.println("test"); } @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } public class exPhoneStateListener extends PhoneStateListener { public void onServiceStateChanged(ServiceState ss) { super.onServiceStateChanged(ss); int state; state=ss.getState(); switch(state) { case ServiceState.STATE_IN_SERVICE: ib_state=1; break; case ServiceState.STATE_OUT_OF_SERVICE: ib_state=0; break; } Intent i=new Intent("SERVICE_STATE"); i.putExtra("STATE", ib_state); sendBroadcast(i); } } }