導航:首頁 > 操作系統 > androidwifiservice

androidwifiservice

發布時間:2023-05-25 11:03:15

⑴ 如何從C++代碼直接訪問android framework層的WifiService

說到底,java層的service就是就C++層的binder的封裝,所以從原理上來講通過C++代碼直接訪問android framework層唯洞的service是完全可能的,這篇文章以訪問WifiService為例,講解如何去實現這個功能。

費話少說,直接上代碼:

WifiTest.cpp

[cpp] view plain在CODE上查看代碼片派生到我的代碼片
#include <sys/types.h>
#include <unistd.h>
#include <grp.h>

#include <binder/IPCThreadState.h>
#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
#include <utils/Log.h>

#include <utils/String16.h>
//#include <utils/Vector.h>
#include <槐攔utils/List.h>
#include <utils/PropertyMap.h>

using namespace android;

#define WIFI_SERVICE "wifi"
const String16 WIFI_DESCRIPTOR("android.net.wifi.IWifiManager");

class ScanResult
{

private:
ScanResult& operator=(const ScanResult& o);

public:
ScanResult(const ScanResult& o):
mSsid(o.mSsid),mBssid(o.mBssid),mCaps(o.mCaps),mLevel(o.mLevel),mFrequency(o.mFrequency),mTimestamp(o.mTimestamp)
{
}

ScanResult(String8 ssid,String16 bssid,String16 caps,int level,int freq,int64_t timeStamp):
mSsid(ssid),mBssid(bssid),mCaps(caps),mLevel(level),mFrequency(freq),mTimestamp(timeStamp)
{
}
void mp()
{
char temp[130];
int size;
memset(temp,0,sizeof(temp));
printf("ssid %s \n",mSsid.string());

size = mBssid.size();
if(size > sizeof(temp)/2 - 1)
{
size = sizeof(temp)/2 - 1;
}
utf16_to_utf8(mBssid.string(), size, temp);
printf("Bssid %s \n"鉛山胡,temp);

size = mCaps.size();
if(size > sizeof(temp)/2 - 1)
{
size = sizeof(temp)/2 - 1;
}
utf16_to_utf8(mCaps.string(), size, temp);
printf("ssid %s \n",temp);

printf("level %d \n",mLevel);
printf("freq %d \n",mFrequency);
printf("freq %ld \n",mTimestamp);
}
private:
String8 mSsid;
String16 mBssid;
String16 mCaps;
int mLevel;
int mFrequency;
int64_t mTimestamp;
};

class IWifiService: public android::IInterface {
public:
DECLARE_META_INTERFACE(WifiService)

virtual void startScan(int forceActive) = 0;
virtual int getScanResults(List<ScanResult> &list) = 0;
virtual bool setWifiEnabled(bool enable) = 0;
};

class BpWifiService: public android::BpInterface<IWifiService>
{
enum
{
FIRST_CALL_TRANSACTION = 1,
TRANSACTION_getConfiguredNetworks = (android::IBinder::FIRST_CALL_TRANSACTION + 0),
TRANSACTION_addOrUpdateNetwork = (android::IBinder::FIRST_CALL_TRANSACTION + 1),
TRANSACTION_removeNetwork = (android::IBinder::FIRST_CALL_TRANSACTION + 2),
TRANSACTION_enableNetwork = (android::IBinder::FIRST_CALL_TRANSACTION + 3),
TRANSACTION_disableNetwork = (android::IBinder::FIRST_CALL_TRANSACTION + 4),
TRANSACTION_pingSupplicant = (android::IBinder::FIRST_CALL_TRANSACTION + 5),
TRANSACTION_startScan = (android::IBinder::FIRST_CALL_TRANSACTION + 6),
TRANSACTION_getScanResults = (android::IBinder::FIRST_CALL_TRANSACTION + 7),
TRANSACTION_disconnect = (android::IBinder::FIRST_CALL_TRANSACTION + 8),
TRANSACTION_reconnect = (android::IBinder::FIRST_CALL_TRANSACTION + 9),
TRANSACTION_reassociate = (android::IBinder::FIRST_CALL_TRANSACTION + 10),
TRANSACTION_getConnectionInfo = (android::IBinder::FIRST_CALL_TRANSACTION + 11),
TRANSACTION_setWifiEnabled = (android::IBinder::FIRST_CALL_TRANSACTION + 12),
TRANSACTION_getWifiEnabledState = (android::IBinder::FIRST_CALL_TRANSACTION + 13),
TRANSACTION_setCountryCode = (android::IBinder::FIRST_CALL_TRANSACTION + 14),
TRANSACTION_setFrequencyBand = (android::IBinder::FIRST_CALL_TRANSACTION + 15),
TRANSACTION_getFrequencyBand = (android::IBinder::FIRST_CALL_TRANSACTION + 16),
TRANSACTION_isDualBandSupported = (android::IBinder::FIRST_CALL_TRANSACTION + 17),
TRANSACTION_saveConfiguration = (android::IBinder::FIRST_CALL_TRANSACTION + 18),
TRANSACTION_getDhcpInfo = (android::IBinder::FIRST_CALL_TRANSACTION + 19),
TRANSACTION_acquireWifiLock = (android::IBinder::FIRST_CALL_TRANSACTION + 20),
TRANSACTION_updateWifiLockWorkSource = (android::IBinder::FIRST_CALL_TRANSACTION + 21),
TRANSACTION_releaseWifiLock = (android::IBinder::FIRST_CALL_TRANSACTION + 22),
TRANSACTION_initializeMulticastFiltering = (android::IBinder::FIRST_CALL_TRANSACTION + 23),
TRANSACTION_isMulticastEnabled = (android::IBinder::FIRST_CALL_TRANSACTION + 24),
TRANSACTION_acquireMulticastLock = (android::IBinder::FIRST_CALL_TRANSACTION + 25),
TRANSACTION_releaseMulticastLock = (android::IBinder::FIRST_CALL_TRANSACTION + 26),
TRANSACTION_setWifiApEnabled = (android::IBinder::FIRST_CALL_TRANSACTION + 27),
TRANSACTION_getWifiApEnabledState = (android::IBinder::FIRST_CALL_TRANSACTION + 28),
TRANSACTION_getWifiApConfiguration = (android::IBinder::FIRST_CALL_TRANSACTION + 29),
TRANSACTION_setWifiApConfiguration = (android::IBinder::FIRST_CALL_TRANSACTION + 30),
TRANSACTION_startWifi = (android::IBinder::FIRST_CALL_TRANSACTION + 31),
TRANSACTION_stopWifi = (android::IBinder::FIRST_CALL_TRANSACTION + 32),
TRANSACTION_addToBlacklist = (android::IBinder::FIRST_CALL_TRANSACTION + 33),
TRANSACTION_clearBlacklist = (android::IBinder::FIRST_CALL_TRANSACTION + 34),
TRANSACTION_getWifiServiceMessenger = (android::IBinder::FIRST_CALL_TRANSACTION + 35),
TRANSACTION_getWifiStateMachineMessenger = (android::IBinder::FIRST_CALL_TRANSACTION + 36),
TRANSACTION_getConfigFile = (android::IBinder::FIRST_CALL_TRANSACTION + 37),
TRANSACTION_captivePortalCheckComplete = (android::IBinder::FIRST_CALL_TRANSACTION + 38),
};
public:
BpWifiService(const android::sp<android::IBinder>& impl): android::BpInterface<IWifiService>(impl)
{
}

void startScan(int forceActive)
{
android::Parcel data, reply;
data.writeInterfaceToken(WIFI_DESCRIPTOR);
if (forceActive)
{
data.writeInt32(1);
}
else
{
data.writeInt32(0);
}
remote()->transact(TRANSACTION_startScan, data, &reply, 0);
}

virtual int getScanResults(List<ScanResult> &list)
{
Parcel data, reply;
data.writeInterfaceToken(WIFI_DESCRIPTOR);
remote()->transact(TRANSACTION_getScanResults, data, &reply, 0);
if (0 != reply.readExceptionCode())
{
return 0;
}
int count = reply.readInt32();
for (int i=0;i<count;i++)
{
String8 ssid;
int res = reply.readInt32();
if (res != 0)
{
reply.readInt32();
reply.readInt32();
int length = reply.readInt32();
ssid = String8((const char*)reply.readInplace(length),length);
}

// utf16_to_utf8(const char16_t* src, size_t src_len, char* dst);

String16 BSSID = reply.readString16();
String16 caps = reply.readString16();
int level = reply.readInt32();
int frequency = reply.readInt32();
int64_t timestamp = reply.readInt64();
ScanResult result(ssid,BSSID,caps,level,frequency,timestamp);
list.push_back(result);
}
return count;
}

bool setWifiEnabled(bool enable)
{
Parcel data, reply;
data.writeInterfaceToken(WIFI_DESCRIPTOR);

if(enable)
data.writeInt32(1);
else
data.writeInt32(0);
remote()->transact(TRANSACTION_setWifiEnabled, data,&reply,0);
reply.readExceptionCode();
return 0!=reply.readInt32();
}

};

IMPLEMENT_META_INTERFACE(WifiService, WIFI_DESCRIPTOR)

int main(int argc, char *argv[])
{

android::sp<android::IServiceManager> sm = android::defaultServiceManager();
android::sp<android::IBinder> binder;
android::sp<IWifiService> wifi;

binder = sm->getService(android::String16(WIFI_SERVICE));

if (binder == 0)
{
return 1;
}

wifi = android::interface_cast<IWifiService>(binder);

wifi->setWifiEnabled(true);
printf("+++++scan start");
wifi->startScan(1);

for(int i=0;i<10;i++)
{
usleep(1*1000*1000);
List<ScanResult> list;
wifi->getScanResults(list);
if(list.size() > 0)
{
for(List<ScanResult>::iterator it = list.begin();it != list.end();++it)
{
(*it).mp();
}
break;
}
}

return(0);
}

基本的思路很簡單:
先通過:
android::defaultServiceManager()->getService(android::String16(WIFI_SERVICE));
獲取binder介面,再通過Parcel讀與binder,具體的實現可以參考IWifiManager.java的代碼。

編譯後運行以上的代碼可以得到類似以下的輸出:

ssid wifitest
Bssid b8:55:10:84:13:57
ssid [WPA-PSK-CCMP][WPA2-PSK-CCMP][WPS][ESS]
level -55
freq 2447
time stamp 1073922473
ssid test
Bssid 08:bd:43:c3:a9:96
ssid [WPA2-PSK-CCMP][WPS][ESS]
level -66
freq 2462
time stamp 1073922473

⑵ Android 怎樣默認打開攜帶型WIFI熱點 M

目前判斷Wifi開機後是否需要的自動開啟或燃實現是在wifiService.java的checkAndStartWifi() 函數里,類似的,可以參照wifi在wifiService.java里添加一下如下函數:
public void checkAndStartSoftAp() {
mWifiStateMachine.autoConnectInit();
boolean isAirplaneModeOn = isAirplaneModeOn();
int persistedWifiState = getPersistedWifiState();
SXlog.d(TAG, isAirplaneModeOn: + isAirplaneModeOn + , getPersistedWifiState: + persistedWifiState);
mAirplaneModeOn.set(isAirplaneModeOn);
mPersistWifiState.set(persistedWifiState);

if (mWifiStateMachine.hasCustomizedAutoConnect() && mAirplaneModeOn.get()) { //AirplaneMode下不打開SoftAp,客戶也可以看情況腔臘不限制
SXlog.i(TAG, Don't enable softAp when airplane mode is on for customization.);
} else {
Slog.i(TAG, WifiService starting up with softAp);

setWifiApEnabled(null, true);
} } 然後,在systemServer.java里搜索wifi.checkAndStartWifi(), 可以找見它在衫圓虛ServerThread的run里,將wifi.checkAndStartWifi()替換成wifi.checkAndStartSoftAp(),然後,編譯測試。

⑶ 在android上查看wifi狀態,代碼如下:

不知道你的程序報的是什麼錯,給你一個例子吧,不過方法和你的有點差別:
public class WifiAdmin {
/**WiFi Manager**/
private WifiManager wifimanager;
/**WiFi Information**/
private WifiInfo wifiinfo;
/**Activity NetWork List**/
private List<ScanResult> netlist;
/**Configured NetWork List**/
private List<WifiConfiguration> connectedlist;
/**WiFi Lock**/
private WifiLock wifilock;

public WifiAdmin(Context context) {
wifimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}

/**
* WiFi Operate
* */
/**Open WiFi**/
public void openWifi() {
if (!wifimanager.isWifiEnabled()) {
wifimanager.setWifiEnabled(true);
}
}
/**Close WiFi**/
public void closeWifi() {
if (wifimanager.isWifiEnabled()) {
wifimanager.setWifiEnabled(false);
}
}
/**WiFi State**/
public int checkState() {
return wifimanager.getWifiState();
}

/**
* WiFiLock Operate
* */
/**Create WiFiLock**/
public void creatWifiLock() {
wifilock = wifimanager.createWifiLock("Test");
}
/**Lock WiFi**/
public void acquireWifiLock() {
wifilock.acquire();
}
/**Clear WiFiLock**/
public void releaseWifiLock() {
if (wifilock.isHeld()) {
wifilock.release();
}
}
/**
* WiFiInfo Operate
* */
/**Get WiFiInfo**/
public WifiInfo getWifiInfo(){
wifiinfo = wifimanager.getConnectionInfo();
return wifiinfo;
}

/**
* NetWork Operate
* */
/**Scan**/
public void startScan() {
wifimanager.startScan();
netlist = wifimanager.getScanResults();
connectedlist = wifimanager.getConfiguredNetworks();
}
/**Get Configured NetWork**/
public List<WifiConfiguration> getConfiguration() {
return connectedlist;
}
/**Get Activity NetWork**/
public List<ScanResult> getWifiList() {
return netlist;
}
/**Connect a NetWork**/
public void connectConfiguration(int index) {
if (index < 0 || index > connectedlist.size()) {
return;
}
wifimanager.enableNetwork(connectedlist.get(index).networkId,true);
}
/**Add a NetWork**/
public void addNetwork(WifiConfiguration wcg) {
int wcgID = wifimanager.addNetwork(wcg);
wifimanager.enableNetwork(wcgID, true);
}
/**DisConnect a NetWork**/
public void disconnectWifi(int netId) {
wifimanager.disableNetwork(netId);
wifimanager.disconnect();
}
}

⑷ Android中怎麼打開Wifi的組播功能

打開Android中Wifi的組播功能。主要有以下幾個步驟:
在Manifest文件中加入:android.permission.CHANGE_WIFI_MULTICAST_STATE,這個許可權
獲取到MulticastLock對象,這個對象不能直接實例化,要通過WifiManager間接得到,工廠模式
調用MulticastLock對象的acquire方法,獲取到組播鎖
相應的,用完組播,為了不浪費電力,要調用MulticastLock的release方法釋放鎖
下面寫了個簡單示例,通過組播發現伺服器。
Activity寫的比較簡單
public class MulticastDemoActivity extends Activity {
MulticastLock multicastLock;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
allowMulticast();
try {
NetUtil.findServerIpAddress();
} catch (IOException e) {
throw new RuntimeException(e);
}
Log.d("multicast.demo", "find ip ok.");
multicastLock.release();
}
private void allowMulticast(){
WifiManager wifiManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);
multicastLock=wifiManager.createMulticastLock("multicast.test");
multicastLock.acquire();
}
}
在Activity中打開和釋放組播鎖。使用組播發送報文和接收ip地址信息的工具類代碼:
public class NetUtil {
private static final String TAG="Net.Utils";
private static final int MULTICAST_PORT=5111;
private static final String GROUP_IP="224.5.0.7";
private static byte[] sendData;
static{
sendData=new byte[4];
// 0xEE78F1FB
sendData[3] = (byte) 0xEE;
sendData[2] = (byte) 0×78;
sendData[1] = (byte) 0xF1;
sendData[0] = (byte) 0xFB;
}
public static String findServerIpAddress() throws IOException{
String ip=null;
MulticastSocket multicastSocket=new MulticastSocket(MULTICAST_PORT);
multicastSocket.setLoopbackMode(true);
InetAddress group = InetAddress.getByName(GROUP_IP);
multicastSocket.joinGroup(group);
DatagramPacket packet=new DatagramPacket(sendData, sendData.length,group,MULTICAST_PORT);
for(;;){
multicastSocket.send(packet);
Log.d(TAG,">>>send packet ok");
byte[] receiveData=new byte[256];
packet=new DatagramPacket(receiveData, receiveData.length);
multicastSocket.receive(packet);
String packetIpAddress=packet.getAddress().toString();
packetIpAddress=packetIpAddress.substring(1, packetIpAddress.length());
Log.d(TAG,"packet ip address: "+packetIpAddress);
StringBuilder packetContent=new StringBuilder();
for(int i=0;i<receiveData.length;i++){
if(receiveData[i]==0){
break;
}
packetContent.append((char)receiveData[i]);
}
ip=packetContent.toString();
Log.d(TAG,"packet content ip is: "+ip);
if(ip.equals(packetIpAddress)){
Log.d(TAG,"find server ip address: "+ip);
break;
}else{
Log.d(TAG,"not find server ip address, continue …");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
return ip;
}
}

⑸ 如何從C++代碼直接訪問android framework層的WifiService

在寫android代碼時,我們基本不會出現new MyActivity(), new MyService()等等這樣的代碼,要知道android app的編寫語言是java,java的特點是什麼:「一切皆對象」。那麼問題來了,我們寫的activity,service等什麼時候被new出來了的呢,它們是怎樣被new出來的,帶著這個問題我們繼續看下去。 android framework層架構採用了ioc方式,程序員實現的activity,service等式在android的框架層new出來的,程序猿在完成一個activity後都需要在mainfest注冊。然後android framework層利用反射的方式動態的創建其對象。所以android採用這樣的方式將控制權全部掌握在框架層,客戶端清則程序員只需要按照其方式實現就行。 但是緊接著新的問題又會出現,既然我們客戶端程序員不需要new 組件對象,也就是說我們的各個組件間是相互獨立的。然後新的問題產生各組件之間的交互該如何處理呢,android framework為我們想到了這個問題,所以Intent信使產生了,android設計者通過Intent信使實現各個組件間的交互,不得不說框架的設計確實很好,這里膜拜大神。 銷鍵android的框架層牢牢掌控住客戶端的,包括對象的創建調用等。其中運用的很多好的設計模式以及方法值得我們學習。 答斗棚Service 有個onStartCommand()方法,這個方法是在每次調用 startService()方法時,都會調用的一個方法,如果要實現Service一直運行在後台,那麼就可以在onStartCommand方法中做一些處理。另外,這個方法的返回值是一個Int類型的。從Android官方文檔中,我們知道onStartCommand有4種返回值: START_STICKY:如果service進程被kill掉,保留service的狀態為開始狀態,但不保留遞送的intent對象。隨後系統會嘗試重新創建service,由於服務狀態為開始狀態,所以創建服務後一定會調用onStartCommand(Intent,int,int)方法。如果在此期間沒有任何啟動命令被傳遞到service,那麼參數Intent將為null。START_NOT_STICKY:「非粘性的」。使用這個返回值時,如果在執行完onStartCommand後,服務被異常kill掉,系統不會自動重啟該服務。START_REDELIVER_INTENT:重傳Intent。使用這個返回值時,如果在執行完onStartCommand後,服務被異常kill掉,系統會自動重啟該服務,並將Intent的值傳入。START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保證服務被kill後一定能重啟。

⑹ 如何在android 中獲取Wifi設備的IP地址

1)第一步獲取WifiManager
Get an instance of this class by calling Context.getSystemService(Context.WIFI_SERVICE).
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
通過wifiManager實例可以獲取:
getConfigureNetwork(): wifi的配置網路介面的屬性
getConnectionInfo(): 當前wifi 連接的信息
getDhcpInfo(): 返回DHCP信息
getScanResults():返回可接入點的列表
getWifiState():返回wifi的連接狀態

⑺ android 代碼怎麼實時拿到連接當前wifi熱點的設備信息

WifiManager wifi_service = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiinfo = wifi_servicemask + "亂者"); Log.v("dns1", dhcpinfo.dns1 + ""); Log.v("dns1", dhcpinfo.dns2 + ""); Log.v("serverAddress"宏配, dhcpinfo.serverAddress + ""蔽陪指);

⑻ android應用有一個開機自動聯網的service,但手機開機時沒有連上WiFi,service會不會中斷

如果你的呢移動數據是開啟的,是不會斷的,而在您連好wifi之後,該服務會自動切換為WiFi模式

⑼ android開發中如果我想代碼實現打開wifi熱點如何實現

1·申請許可權:
android.permission.ACCESS_WIFI_STATE
android.permission.CHANGE_WIFI_STATE
android.permission.WAKE_LOCK
2·獲取WifiManager
wifiManager
=
(WifiManager)
this.getSystemService(Context.WIFI_SERVICE);
3·開啟、關閉wifi
if
(wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
}
else
{
wifiManager.setWifiEnabled(true);
}
4·注意
如果遇到force-close,
選wait即可,
因為啟動wifi需要幾秒鍾,
UI如果5妙鍾還沒反映的話,
系統會給你這個force
close
exception
PS:我以前做過設計讀取系統硬體信息的時候用敬敬過啟氏,悄稿散但是很長時間沒用了,這段注釋是從網上來的,希望能幫到你。

⑽ android 2.3 通過wifi調用webservice 很慢,怎麼解決

跟蹤發現是Android API里的HttpUrlConnection這個類getOutputStream和getInputStream方法很慢,不是ksoap2的問題,冤枉他了。

解決的途徑是慧激
運升1. 不啟用無線路由的DHCP服務,使用靜態IP,伺服器都使用靜態IP連路由。
2. 如何在平板上設置靜態IP,點設置 >> 無線和網路 >旁碧老> Wi-Fi設置 >> 點擊菜單按鈕(屏幕下邊三個按鈕最左邊一個) >> 高級 >> 使用靜態IP 勾上 >> 設置 IP地址,網關,網路掩碼,域名1(一定記得輸入0.0.0.0),最後點擊菜單按鈕選保存。

只要保證平板使用靜態IP連上無線路由,並且域名為0.0.0.0,安卓就不會再花20S+通過DNS解釋什麼域名了。
我在多台平板上測試多沒有問題。

閱讀全文

與androidwifiservice相關的資料

熱點內容
手機淘寶登錄怎麼加密碼 瀏覽:481
linux快捷方式圖標 瀏覽:33
陽光車險的app叫什麼名字 瀏覽:461
購買單片機的器件時需要給商家啥 瀏覽:534
並行編譯技術的發展 瀏覽:549
阿里雲伺服器安裝管理 瀏覽:550
java手機開發教程 瀏覽:674
我的世界怎麼刪除伺服器數據 瀏覽:671
linux內存子系統 瀏覽:972
加密思維幣 瀏覽:690
魅族訪客文件夾 瀏覽:52
添加的文件夾怎麼找 瀏覽:617
程序員涉黃 瀏覽:700
maven編譯resources下的js 瀏覽:521
ubuntu文件移動命令 瀏覽:229
安卓i怎麼查找蘋果手機 瀏覽:951
雲伺服器宕機概率 瀏覽:232
在線買葯用什麼app知乎 瀏覽:815
ubuntu解壓xz文件 瀏覽:676
宏傑加密時電腦關機 瀏覽:390