public class BootBroadcastReceiver extends BroadcastReceiver{
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final String className = "com.example.notify.GameService";
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context. CONNECTIVITY_SERVICE);
NetworkInfo gprs = manager
.getNetworkInfo(ConnectivityManager. TYPE_MOBILE);
NetworkInfo wifi = manager
.getNetworkInfo(ConnectivityManager. TYPE_WIFI);
if (!gprs.isConnected() && !wifi.isConnected()) { //网络没开
// network closed
} else { //如果检测到有网络就发送请求确认通知时间
Log. e("开机自动服务检测到网络" , "开机自动服务自动启动....." );
sendMsg(context);
}
}
private void sendMsg(Context context) {
//后边的XXX.class就是要启动的服务
Intent service = new Intent(context,GameService. class);
context.startService(service);
//sentHttp();
//beepForAnHour();
ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
while(true){//等待服务启动后开始发送广播
if(waitService(mActivityManager)){
break;
}
try {
Thread. sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//启动之后再等1秒,必须保证比 creat迟才行
try {
Thread. sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//发起另一个通知给监听该消息的监听器,前提是处理该消息的服务需要已经启动
Intent ntf = new Intent( "com.skymobile.empresses.NTF");
context.sendBroadcast(ntf);
Log.e("开机自动服务sendMsg" , "开机自动服务自动启动....." );
}
private boolean waitService(ActivityManager mActivityManager) {
List<RunningServiceInfo> mServiceList = mActivityManager.getRunningServices(40);
for( int i = 0; i < mServiceList.size(); i ++){
if( className.equals(mServiceList.get(i). service.getClassName())){
Log. e("开机自动服务waitService" , "服务启动" );
return true;
}
}
return false;
}
}