我正在使用 Eclipse,android sdk 3.2
但在connection is lost
.
首先我检查了网络的类型以确保我理解得很好:
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE)
.isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting();
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null)
Toast.makeText(getApplicationContext(), info.getTypeName(),
Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Pas de connexion",
Toast.LENGTH_LONG).show();
if (!is3g)
Log.i("Network Listener", "DISCONNECTED");
else
Log.i("Network Listener", "CONNECTED");
==> 这是一个移动网络,我已连接
然后我按 F8 或者我做:
telnet localhost 5554
gsm data off
停止连接
这是我dynamic broadcast receiver
的活动:
public class ActivityA extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.query);
this.registerReceiver(this.networkStateReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
//i have tried several things : State networkState = networkInfo.getState();
// if (networkState.compareTo(State.DISCONNECTED) == 0) ...
if (networkInfo != null && networkInfo.isConnected()) {
Toast.makeText(getApplicationContext(), "CONNECTED",
Toast.LENGTH_LONG).show();
Log.i("Network Listener", "Connected");
} else {
Toast.makeText(getApplicationContext(), "DISCONNECTED",
Toast.LENGTH_LONG).show();
Log.i("Network Listener", "Network Type Changed");
Intent offline = new Intent(AccountInfoActivity.this,
OfflineWorkService.class);
startService(offline);
}
};
我的清单:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
问题是:当activityA启动时,我的广播接收到一些东西,它显示“已连接”(日志)和我的吐司。当我手动关闭连接时,什么也没发生。我的服务没有启动,日志消息没有显示,只有 toast 消息有效......
更好的是,当我再次打开连接时 ( by pressing F8
),我再次测试连接类型,显示 Toast 消息,但这次 Log 消息不起作用。按 F8 时出现问题。无论如何,我想我错过了广播接收器的一些东西,这并不完全清楚。
请帮我。