出处:http://blog.csdn.net/djy1992/article/details/9629741 需代码留邮箱
如果现在系统只发送一个一次性广播(比如开机启动),
接收器只识别一次,因为系统不继续发送该广播了;
现在是要在这种情况下开启服务(开机启动服务),
而且要连续的监听变化(如:网络改变时,该服务启动),该怎么处理?
第一步:在manifest注册广播接收器,
<receiver android:name=".service.ClientUpdateReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>// 开机启动发送的广播命令
<category android:name="android.intent.category.HOME"/>
</intent-filter>
</receiver>
第二步:在代码中编写广播接收器,
public class ClientUpdateReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Intent i = new Intent();
i.setAction("zte.com.market.service");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(i);
}
}
第三步:编写service类,其中需要另外编写一个广播接收器,方便实时接受广播,
public class UpdateService extends Service
{
private ConnectivityManager connectivityManager;
private NetworkInfo info;
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.d("Jeny", "网络状态已经改变");
connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
info = connectivityManager.getActiveNetworkInfo();
if(info != null && info.isAvailable()) {
String name = info.getTypeName();
Log.d("Jeny", "当前网络名称:" + name);
Intent i = new Intent();
i.setAction("zte.com.market.service");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(i);// 开启服务
} else {
Log.d("Jeny", "没有可用网络");
}
}
}
};
@Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
Log.v("Jeny", "[UpdateService]...onDestroy");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// TODO Auto-generated method stub
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
Log.v("Jeny", "mobileInfo.isConnected()------->"+mobileInfo.isConnected()+" wifiInfo.isConnected()---------->"+wifiInfo.isConnected());
if(mobileInfo.isConnected() || wifiInfo.isConnected()){
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
IntentFilter mFilter = new IntentFilter();
mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, mFilter);// 开机启动时首次开启服务后注册接收器
}
}
到此结束!