问题描述
亲爱的程序员你好我正在应用程序中使用android studio开发一个android简单的wifi直接聊天应用程序我基本上有一个连接状态的文本视图,它告诉我设备是wifi直接组中的主机还是客户端,或者如果它断开一个按钮,打开 wifi 设置,然后您转到 wifi direct 并手动连接到另一台设备。 之后,您可以返回应用程序并使用编辑文本框编写消息并使用发送按钮发送它。 我正在使用三种设备进行测试: - 一个旧的三星 S4 与 android 版本 5 -a huawei mate 9 with android version 9 - 带有 android 版本 10 的三星 note 10
我面临两个问题: 第一个问题是,当我尝试将应用程序与 Note 10(或任何其他 API 级别 10 设备)连接并返回到应用程序后,wifi 直连无法与我的应用程序 IDK 一起使用,为什么还在文本视图不显示它是主机还是客户端,即使它在我连接的其他设备上显示此信息
另一个问题是,当我连接 huawei 和 s4 时,应用程序在 s4 上正常运行,它向华为发送消息,华为中的文本视图显示这些消息,但如果我尝试相反,应用程序崩溃并给出我出现以下错误
E/e.wifip2p_take: [qarth_debug:] get PatchStore::createdisableExceptionQarthFile method fail.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.wifip2p_take2,PID: 1388
android.os.networkonmainthreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1523)
at java.net.socketoutputStream.socketWrite(SocketoutputStream.java:116)
at java.net.socketoutputStream.write(SocketoutputStream.java:149)
at com.example.wifip2p_take2.MainActivity$sendReceive.write(MainActivity.java:229)
at com.example.wifip2p_take2.MainActivity$4.onClick(MainActivity.java:114)
at android.view.View.performClick(View.java:6659)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:6631)
at android.view.View.access$3100(View.java:790)
at android.view.View$PerformClick.run(View.java:26187)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
我的 manafist 文件
<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
我的主要活动代码:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
TextView status,messageTV;
Button send,connect;
EditText messageET;
boolean isHost;
wifip2pManager manager;
wifip2pManager.Channel channel;
broadcastReceiver receiver;
IntentFilter intentFilter;
server server;
client client;
sendReceive sendReceive;
static final int MESSAGE_READ = 1;
Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
switch (msg.what){
case MESSAGE_READ:
byte [] readBuffer =(byte []) msg.obj;
String temp = new String(readBuffer,msg.arg1);
messageTV.setText(temp);
Log.d(TAG,"handleMessage: The Other side Says:"+temp);
break;
}
return true;
}
});
private void initializework() {
status = findViewById(R.id.statusTV);
messageTV = findViewById(R.id.messageTV);
send = findViewById(R.id.sendBtn);
connect = findViewById(R.id.connectBtn);
messageET= findViewById(R.id.messageEditText);
manager = (wifip2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this,getMainLooper(),null);
receiver = new WiFiDirectbroadcastReceiver(manager,channel,this);
intentFilter = new IntentFilter();
intentFilter.addAction(wifip2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(wifip2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(wifip2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(wifip2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializework();
listeners();
}
private void listeners() {
status.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
status.setText("Hello ?");
status.setTextColor(Color.parseColor("#000000"));
}
});
connect.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openWifiSettings();
}
});
send.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = messageET.getText().toString();
sendReceive.write(message.getBytes());
}
});
}
private void openWifiSettings() {
final Intent intent = new Intent(Intent.ACTION_MAIN,null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.android.settings","com.android.settings.wifi.WifiSettings");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity( intent);
}
wifip2pManager.ConnectionInfoListener mConnectionInfoListener = new wifip2pManager.ConnectionInfoListener() {
@Override
public void onConnectionInfoAvailable(wifip2pInfo info) {
final InetAddress groupOwnerAddress = info.groupOwnerAddress;
if (info.groupFormed && info.isGroupOwner) {
isHost = true;
status.setText("Host");
status.setTextColor(Color.parseColor("#a4c639"));
Log.d(TAG,"onConnectionInfoAvailable: this device is the HOST in the wifiDirect group");
server = new server();
server.start();
} else if (info.groupFormed) {
isHost = false;
status.setText("Client");
status.setTextColor(Color.parseColor("#a4c639"));
Log.d(TAG,"onConnectionInfoAvailable: this device is the CLIENT in the wifiDirect
group");
client = new client(groupOwnerAddress);
client.start();
}
}
};
public class server extends Thread{
Socket connectionSocket;
ServerSocket serverSocket;
@Override
public void run() {
try {
serverSocket = new ServerSocket(6666);
connectionSocket = new Socket();
connectionSocket = serverSocket.accept();
sendReceive=new sendReceive(connectionSocket);
sendReceive.start();
} catch (IOException e) {
Log.d(TAG,"Server run: Failed to run server socket. exception: "+e);
}
}
}
public class client extends Thread{
Socket connectionSocket;
InetAddress hostAddress;
public client(InetAddress hostAddress) {
this.hostAddress = hostAddress;
connectionSocket = new Socket();
}
@Override
public void run() {
try {
connectionSocket.connect(new InetSocketAddress(hostAddress,6666),500);
sendReceive= new sendReceive(connectionSocket);
sendReceive.start();
} catch (IOException e) {
Log.d(TAG,"Client run: Failed to run client socket. exception: "+e);
}
}
}
public class sendReceive extends Thread{
private Socket connectionSocket;
private InputStream inputStream;
private OutputStream outputStream;
public sendReceive(Socket socket) {
connectionSocket = socket;
try {
inputStream = connectionSocket.getInputStream();
outputStream = connectionSocket.getoutputStream();
}catch (IOException e){
Log.d(TAG,"sendReceive: Failed to get input or output stream");
}
}
@Override
public void run() {
byte[] buffer=new byte[2048];
int bytes;
while (connectionSocket!=null)
{
try {
bytes=inputStream.read(buffer);
if (bytes>0)
{
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
}
} catch (IOException e) {
Log.d(TAG,"Reading message run: something went wrong exception:"+e);
}
}
}
public void write(byte[] bytes)
{
try {
outputStream.write(bytes);
} catch (IOException e) {
Log.d(TAG,"sendReceive write: Failed to write output stream");
}
}
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver,intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
}
我的 WiFiDirectbroadcastReceiver 活动代码:
public class WiFiDirectbroadcastReceiver extends broadcastReceiver{
private static final String TAG ="wifi direct app broadCast Receiver";
private wifip2pManager manager;
private wifip2pManager.Channel channel;
private MainActivity mainActivity;
public WiFiDirectbroadcastReceiver(wifip2pManager manager,wifip2pManager.Channel channel,MainActivity mainActivity) {
this.manager = manager;
this.channel = channel;
this.mainActivity = mainActivity;
}
@SuppressLint("LongLogTag")
@Override
public void onReceive(Context context,Intent intent) {
String action = intent.getAction();
if (wifip2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Determine if Wifi Direct mode is enabled or not,alert
int state = intent.getIntExtra(wifip2pManager.EXTRA_WIFI_STATE,-1);
if (state == wifip2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi P2P is enabled
Toast.makeText(context,"WifiDirect Enabled",Toast.LENGTH_SHORT).show();
} else {
// Wi-Fi P2P is not enabled
Toast.makeText(context,"WifiDirect disabled",Toast.LENGTH_SHORT).show();
}
} else if (wifip2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// The peer list has changed! We should probably do something about that
} else if (wifip2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Connection state changed! We should probably do something about that
if(manager != null){
NetworkInfo mNetworkInfo = intent.getParcelableExtra(wifip2pManager.EXTRA_NETWORK_INFO);
if (mNetworkInfo.isConnected()){
manager.requestConnectionInfo(channel,mainActivity.mConnectionInfoListener);
}else {
mainActivity.status.setText("Device disconnected");
Log.d(TAG,"onReceive: connection ended. device disconnected ");
}
}
} else if (wifip2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)