Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 利用廣播BroadCast監聽網絡的變化

利用廣播BroadCast監聽網絡的變化

編輯:關於Android編程

package com.app.test02;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.widget.Toast;
/**
 * Android  利用廣播BroadCast監聽網絡的變化
 * @author 402-9
 */
public class BroadCastDemo extends BroadcastReceiver{
	State wifiState = null;
	State mobileState = null;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		//獲取手機的連接服務管理器,這裡是連接管理器類
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);	
		wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();	
		mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();

		Intent intent2 = new Intent(context , BroadCastActivity2_SMS.class);
		if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED == mobileState) {
			context.startService(intent2);
			Toast.makeText(context, "手機網絡連接成功!", Toast.LENGTH_SHORT).show();
		} else if (wifiState != null && mobileState != null && State.CONNECTED == wifiState && State.CONNECTED != mobileState) {
			context.startService(intent2);
			Toast.makeText(context, "無線網絡連接成功!", Toast.LENGTH_SHORT).show();
		} else if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED != mobileState) {
			context.startService(intent2);
			Toast.makeText(context, "手機沒有任何網絡...", Toast.LENGTH_SHORT).show();
		}
	}

}


 

        <receiver android:name=".BroadCastDemo">
            <intent-filter >
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>


 

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

\

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved