How to connect multiple clients to one host via Wifi P2P - java

I'm trying to create a WiFiP2P to communicate with 2 android phones and one Raspberry Pi. I want one phone as host and the second phone + Raspberry Pi as clients.
Until know i could create a test APP to connect the 2 phones via Wifi direct (tested successful). I was following a great tutorial on Youtube Wifi P2P. Unfortunately the tutorial just show how to connect one host with one client and not multiple clients.
I was trying to follow the Android developer guide, but I have not enough experience to understand everything.
I hope you guys can help me to understand what I have to change in my code and explain me why.
The following code is the exact copy from the mentioned tutorial.
Here my MainActivity:
package com.example.wifip2p;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btnOnOff, btnDiscover, btnSend;
ListView listView;
TextView read_msg_box, connectionStatus;
EditText writeMsg;
WifiManager wifiManager;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
static final int MESSAGE_READ=1;
ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
}
initialWork();
exqListener();
}
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what){
case MESSAGE_READ:
byte[] readBuff = (byte[])msg.obj;
String tempMsg = new String(readBuff,0,msg.arg1);
read_msg_box.setText(tempMsg);
break;
}
return true;
}
});
private void exqListener() {
btnOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(false);
btnOnOff.setText("ON");
if(mManager!=null) {
mManager.removeGroup(mChannel, null);
}
}else{
wifiManager.setWifiEnabled(true);
btnOnOff.setText("OFF");
}
}
});
btnDiscover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
connectionStatus.setText("Discovery Started");
}
#Override
public void onFailure(int reason) {
connectionStatus.setText("Discovery Starting Failed");
}
});
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
final WifiP2pDevice device = deviceArray[i];
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(getApplicationContext(),"Connected to " + device.deviceName, Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
});
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = writeMsg.getText().toString();
Toast.makeText(getApplicationContext(),"MSG: " + msg,Toast.LENGTH_SHORT).show();
sendReceive.write(msg.getBytes());
}
});
}
private void initialWork() {
btnOnOff= findViewById(R.id.onOff);
btnDiscover = findViewById(R.id.discover);
btnSend = findViewById(R.id.sendButton);
listView = findViewById(R.id.peerListView);
read_msg_box = findViewById(R.id.readMsg);
connectionStatus = findViewById(R.id.connectionStatus);
writeMsg = findViewById(R.id.writeMsg);
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(),null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if(!peerList.getDeviceList().equals(peers)){
peers.clear();
peers.addAll(peerList.getDeviceList());
deviceNameArray = new String[peerList.getDeviceList().size()];
deviceArray = new WifiP2pDevice[peerList.getDeviceList().size()];
int index = 0;
for(WifiP2pDevice device : peerList.getDeviceList()){
deviceNameArray[index] = device.deviceAddress;
deviceArray[index] = device;
index++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,deviceNameArray);
listView.setAdapter(adapter);
}
if(peers.size()==0){
Toast.makeText(getApplicationContext(), "No Devices Found",Toast.LENGTH_SHORT).show();
}
}
};
WifiP2pManager.ConnectionInfoListener connectionInfoListener = new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
final InetAddress groupOwnerAddress = wifiP2pInfo.groupOwnerAddress;
if(wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner){
connectionStatus.setText("Host");
serverClass=new ServerClass();
serverClass.start();
}else if(wifiP2pInfo.groupFormed){
connectionStatus.setText("Client");
clientClass = new ClientClass(groupOwnerAddress);
clientClass.start();
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver,mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
registerReceiver(mReceiver,mIntentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
clientClass.socket.close();
serverClass.serverSocket.close();
serverClass.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void finalize() throws Throwable {
super.finalize();
try {
clientClass.socket.close();
serverClass.serverSocket.close();
serverClass.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class ServerClass extends Thread{
Socket socket;
ServerSocket serverSocket;
#Override
public void run() {
// serverSocket= null;
// socket = null;
try {
Log.i("ServerSocket is called", "Called");
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket skt){
socket = skt;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while(socket!=null){
try {
bytes = inputStream.read(buffer);
if(bytes > 0){
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write (byte[] bytes){
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientClass extends Thread{
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress){
hostAdd = hostAddress.getHostAddress();
// socket = null;
socket = new Socket();
}
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd,8888),500);
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here my BroadcastReceiver Class:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.nfc.Tag;
import android.util.Log;
import android.widget.Toast;
import static android.content.ContentValues.TAG;
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReceiver(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, MainActivity mActivity)
{
this.mManager = mManager;
this.mChannel = mChannel;
this.mActivity = mActivity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
if(state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
Toast.makeText(context,"Wifi is ON",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context,"Wifi is OFF",Toast.LENGTH_SHORT).show();
}
}else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
if(mManager!=null){
mManager.requestPeers(mChannel,mActivity.peerListListener);
}
Log.d(TAG, "onReceive: P2P peers changed");
}else if(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
if(mManager==null){
return;
}
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()){
mManager.requestConnectionInfo(mChannel,mActivity.connectionInfoListener);
}else{
mActivity.connectionStatus.setText("Device Disconnected");
}
}else if(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
//do something
}
}
}

Related

I'm trying to implement Bluetooth functionality in Android Studio, need some help in connecting problem

I used Bluetooth API and following code is for on/off, show paired devices list, and connect paired devices.
other functions work well, but connecting devices doesn't work .
I try to use thread bidirectional, when bluetooth turns on, serverthread(acceptthread) generated and started. And when I choose device on the list, clientthread(connectthread) generated and started. This is my intent, but when I try to connect on the phone, app is turned off(almost at the client, occasionally at the server).
I thought maybe it's UUID problem so I checked UUID 00enter code here001101-0000-1000-8000-00805F9B34FB, but it didn't help.enter code here
sorry for the import code chunks, I would really appreciate your help.
'''
package com.practice.bluetoothmodule;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
TextView bthStatus;
Button bthOn;
Button bthOff;
Button bthCon;
BluetoothAdapter bthAdapter;
Set<BluetoothDevice> pairedDevices;
List<String> listofPairedDevices;
private String btAddress=null;
BluetoothDevice bthDevice;
AcceptThread acceptThread;
ConnectThread connectThread;
private Handler mHandler = null;
final static int BT_REQUEST_ENABLE=1;
final static UUID BT_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bthStatus = (TextView)findViewById(R.id.text_check);
bthOn = (Button)findViewById(R.id.bth_on);
bthOff=(Button)findViewById(R.id.bth_off);
bthCon=(Button)findViewById(R.id.dev_con);
bthAdapter=BluetoothAdapter.getDefaultAdapter();
bthOn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view){
bluetoothOn();
}
});
bthOff.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view){
bluetoothOff();
}
});
bthCon.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view){
listPairedDevices();
}
});
}
#Override
public void onStart(){
super.onStart();
}
#Override
public void onDestroy(){
super.onDestroy();
if(acceptThread != null){
acceptThread.cancel();
acceptThread=null;
}
if(connectThread != null){
connectThread.cancel();
connectThread=null;
}
}
void bluetoothOn(){
if(bthAdapter == null){
Toast.makeText(getApplicationContext(),"블루투스를 지원하지 않는 기기입니다",Toast.LENGTH_SHORT).show();
}
else{
if(bthAdapter.isEnabled()){
Toast.makeText(getApplicationContext(),"블루투스가 이미 활성화된 상태입니다",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"블루투스가 활성화 되어 있지 않습니다",Toast.LENGTH_SHORT).show();
Intent intentBthEnable = new Intent(bthAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intentBthEnable,BT_REQUEST_ENABLE);
}
}
}
void bluetoothOff(){
if(bthAdapter.isEnabled()){
bthAdapter.disable();
Toast.makeText(getApplicationContext(),"블루투스가 비활성화 되었습니다.",Toast.LENGTH_SHORT).show();
bthStatus.setText("비활성화");
}
else{
Toast.makeText(getApplicationContext(),"블루투스가 이미 비활성화 상태입니다",Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
switch(requestCode){
case BT_REQUEST_ENABLE:
if(resultCode == RESULT_OK){
Toast.makeText(getApplicationContext(),"블루투스 활성화",Toast.LENGTH_LONG).show();
bthStatus.setText("활성화");
start();
} else if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(),"취소",Toast.LENGTH_LONG).show();
bthStatus.setText("비활성화");
}
break;
}
super.onActivityResult(requestCode,resultCode,data);
}
void listPairedDevices(){
if(bthAdapter.isEnabled()){
pairedDevices = bthAdapter.getBondedDevices();
if(pairedDevices.size()>0){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("장치 선택");
listofPairedDevices = new ArrayList();
for(BluetoothDevice device: pairedDevices){
listofPairedDevices.add(device.getName());
}
final CharSequence[] items= listofPairedDevices.toArray(new CharSequence[listofPairedDevices.size()]);
listofPairedDevices.toArray(new CharSequence[listofPairedDevices.size()]);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
connectSelectedDevice(items[item].toString());
}
});
AlertDialog alert=builder.create();
alert.show();
}
else{
Toast.makeText(getApplicationContext(),"페어링된 장치가 없습니다",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(),"블루투스가 비활성화 되어 있습니다.",Toast.LENGTH_LONG).show();
}
}
void connectSelectedDevice(String selectedDeviceName){
for(BluetoothDevice tempDevice: pairedDevices){
if(selectedDeviceName.equals(tempDevice.getName())){
bthDevice=tempDevice;
btAddress=bthDevice.getAddress();
break;
}
}
connect(bthDevice);
//Toast.makeText(getApplicationContext(),"연결 시도"+bthDevice.getName(),Toast.LENGTH_LONG).show();
}
public synchronized void start(){
acceptThread = new AcceptThread();
acceptThread.start();
}
public synchronized void connect(BluetoothDevice device){
connectThread=new ConnectThread(device);
connectThread.start();
}
private class AcceptThread extends Thread{
private final BluetoothServerSocket mmServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp=null;
try{
tmp=bthAdapter.listenUsingRfcommWithServiceRecord("Listen",BT_UUID);
Toast.makeText(getApplicationContext(),"서버 열림",Toast.LENGTH_LONG).show();
}catch(IOException e){
Toast.makeText(getApplicationContext(),"서버 안열림",Toast.LENGTH_LONG).show();
}
mmServerSocket=tmp;
}
public void run(){
BluetoothSocket socket=null;
while(true){
try{
socket=mmServerSocket.accept();
} catch(IOException e){
break;
}
if(socket != null){
Toast.makeText(getApplicationContext(),"연결됨",Toast.LENGTH_SHORT).show();
try{
sleep(3000);
} catch (Exception e){}
}
}
}
public void cancel(){
try{
mmServerSocket.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
private class ConnectThread extends Thread{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device){
BluetoothSocket tmp=null;
mmDevice=device;
try{
tmp=device.createRfcommSocketToServiceRecord(BT_UUID);
//Toast.makeText(getApplicationContext(),"클라 초기화 됨.",Toast.LENGTH_LONG).show();
}catch (IOException e){
//Toast.makeText(getApplicationContext(),"클라 초기화 실패.",Toast.LENGTH_LONG).show();
}
mmSocket=tmp;
//Toast.makeText(getApplicationContext(),"클라 초기화",Toast.LENGTH_LONG).show();
}
public void run() {
try {
bthAdapter.cancelDiscovery();
mmSocket.connect();
Toast.makeText(getApplicationContext(), "클라이언트 연결", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "연결실패", Toast.LENGTH_LONG).show();
}
}
public void cancel(){
try{
mmSocket.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
'''
With Android device, Enable BluetoothHCISnoop log to know , what is happening . It will give the sequential flow on what is happening with Bluetooth communication.
https://www.androidcentral.com/all-about-your-phones-developer-options
The following reasons may be the cause:
1. In your code the device address may be wrong
2. The service UUID which you are trying to connect should be present in the service discovery database of remote bluetooth device
3. The app should wait for connect to happen How to programmatically tell if a Bluetooth device is connected?

BLE Android to iOS chat

I am working on an app that allows Android and IOS devices to communicate to each other using Bluetooth. My IOS application is working fine, but I cannot get the android application to work. I am trying to make the android device my central. The problem I have encountered is that I am not able to scan for devices as when I do I get this message from the Android monitor:
08-07 15:09:30.983 27349-27364/uk.ac.york.androidtoios2
D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf=5.
Can someone tell me what is wrong with my code that is not allowing me to scan for the peripheral IOS device.
MainActivity.java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private BluetoothGatt gatt;
private BluetoothGattCharacteristic inputCharacteristic;
private TextView outputView;
private EditText inputView;
private static final int REQUEST_ENABLE_BT = 1;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void receiveMode(View v) {
int apiVersion = android.os.Build.VERSION.SDK_INT;
if (apiVersion >= Build.VERSION_CODES.LOLLIPOP) {
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
// scan for devices
scanner.startScan(new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
// get the discovered device as you wish
// this will trigger each time a new device is found
BluetoothDevice device = result.getDevice();
}
});
} else {
// targeting kitkat or bellow
bluetoothAdapter.startLeScan(new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
// get the discovered device as you wish
}
});
}
}
// rest of your code that will run **before** callback is triggered since it's asynchronous
public void sendMessage(View v) {
inputCharacteristic.setValue(inputView.getText().toString());
gatt.writeCharacteristic(inputCharacteristic);
}
BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
if (getString(R.string.outputUUID).equals(characteristic.getUuid().toString())) {
final String value = characteristic.getStringValue(0);
runOnUiThread(new Runnable() {
#Override
public void run() {
outputView.setText(value);
}
});
}
}
#Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
MainActivity.this.gatt = gatt;
if (newState == BluetoothProfile.STATE_CONNECTED) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
gatt.discoverServices();
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
List<BluetoothGattService> services = gatt.getServices();
for (BluetoothGattService service : services) {
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic characteristic : characteristics) {
if (getString(R.string.outputUUID).equals(characteristic.getUuid().toString())) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
gatt.setCharacteristicNotification(characteristic, true);
BluetoothGattDescriptor descriptor = characteristic.getDescriptors().get(0);
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
}
} else if (getString(R.string.inputUUID).equals(characteristic.getUuid().toString())) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
inputCharacteristic = characteristic;
}
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputView = (TextView) findViewById(R.id.outputText);
inputView = (EditText) findViewById(R.id.inputText);
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}

How can I stop music on an incoming call?

I have been trying to get my app to stop playing music when the phone is ringing, but it isn't working. I've tried everything, but it seems impossible. Here's the code.
package com.beanie.samples.streaming;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.beanie.samples.streaming.R;
import com.beanie.samples.streaming.MyService;
import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class HomeActivity extends Activity implements OnClickListener {
private static final String TAG = "MyServices";
private final static String RADIO_STATION_URL = "http://195.154.237.162:8936/";
private static final String START_STICKY = null;
Button buttonPlay, buttonStopPlay;
/** Called when the activity is first created.
* Keep this here all the application will stop working */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay.setOnClickListener(this);
}
private ProgressBar playSeekBar;
private MediaPlayer player;
private InputStream recordingStream;
private RecorderThread recorderThread;
private boolean isRecording = false;
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Toast.makeText(this, "Buffering ", percent).show();
Log.i("Buffering", "" + percent);
}
public class GetCallerInfoActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
// register PhoneStateListener
PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
// If phone ringing
if (state==TelephonyManager.CALL_STATE_RINGING) {
stopPlaying();
}
// If incoming call received
if (state==TelephonyManager.CALL_STATE_OFFHOOK) {
stopPlaying();
}
if (state==TelephonyManager.CALL_STATE_IDLE) {
Toast.makeText(getApplicationContext(),"phone is neither ringing nor in a call", Toast.LENGTH_LONG).show();
}
}
};
telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);
}
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
player.setLooping(false); // Set looping
} else if (v == buttonStopPlay) {
Log.d(TAG, "onClick: stopping srvice");
stopPlaying();
}
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
stopRecording();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void startRecording() {
BufferedOutputStream writer = null;
try {
URL url = new URL(RADIO_STATION_URL);
URLConnection connection = url.openConnection();
final String FOLDER_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "Songs";
File folder = new File(FOLDER_PATH);
if (!folder.exists()) {
folder.mkdir();
}
writer = new BufferedOutputStream(new FileOutputStream(new File(FOLDER_PATH
+ File.separator + "sample.mp3")));
recordingStream = connection.getInputStream();
final int BUFFER_SIZE = 100;
byte[] buffer = new byte[BUFFER_SIZE];
while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1 && isRecording) {
writer.write(buffer, 0, BUFFER_SIZE);
writer.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
recordingStream.close();
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
try {
isRecording = false;
if (recordingStream != null) {
recordingStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecorderThread extends Thread {
#Override
public void run() {
isRecording = true;
startRecording();
}
};
}
Could someone please help and implement this? I would appreciate and it and it would help a lot. Also, I have even helped myself by trying.
You need to use the TelephonyManager
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyMgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
The listener object can be created like this
private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
// Test for incoming call, dialing call, active or on hold
if (state==TelephonyManager.CALL_STATE_RINGING || state==TelephonyManager.CALL_STATE_OFFHOOK)
{
stop(); // Put here the code to stop your music
}
super.onCallStateChanged(state, incomingNumber);
}
};
When stopping, or closing your app, remember to call this.
mTelephonyMgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);

Running My App In The Background

I have tried to get this working so that it plays in the background?? why won't it work it looks fine to me??
I am new to java/android development so hope someone can fix the issue and explain what I problem was so I can learn something
Yes I got it to stream so far but once you exit the app the music stops playing
For being new think im doing great must be since I have previous experience with PHP etc..
Thanks ;)
package com.beanie.samples.streaming;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.beanie.samples.streaming.R;
import com.beanie.samples.streaming.MyService;
import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
;
public class HomeActivity extends Activity implements OnClickListener {
private static final String TAG = "MyServices";
private final static String RADIO_STATION_URL = "http://195.154.237.162:8936/";
private static final String START_STICKY = null;
Button buttonPlay, buttonStopPlay;
/** Called when the activity is first created.
* Keep this here all the application will stop working */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay.setOnClickListener(this);
}
private ProgressBar playSeekBar;
private MediaPlayer player;
private InputStream recordingStream;
private RecorderThread recorderThread;
private boolean isRecording = false;
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
public void onClick(View v) {
if (v == buttonPlay) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
startPlaying();
player.setLooping(false); // Set looping
} else if (v == buttonStopPlay) {
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
stopPlaying();
}
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
stopRecording();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
private void startRecording() {
BufferedOutputStream writer = null;
try {
URL url = new URL(RADIO_STATION_URL);
URLConnection connection = url.openConnection();
final String FOLDER_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "Songs";
File folder = new File(FOLDER_PATH);
if (!folder.exists()) {
folder.mkdir();
}
writer = new BufferedOutputStream(new FileOutputStream(new File(FOLDER_PATH
+ File.separator + "sample.mp3")));
recordingStream = connection.getInputStream();
final int BUFFER_SIZE = 100;
byte[] buffer = new byte[BUFFER_SIZE];
while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1 && isRecording) {
writer.write(buffer, 0, BUFFER_SIZE);
writer.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
recordingStream.close();
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
try {
isRecording = false;
if (recordingStream != null) {
recordingStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecorderThread extends Thread {
#Override
public void run() {
isRecording = true;
startRecording();
}
};
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
well, it is stopping because you're asking it to stop.
When the activity goes to background it pauses.
You should run the stream from a service (that stays in the background without issues) and use a bound service to communicate between activity and service http://developer.android.com/guide/components/bound-services.html

Android NIO Server Selectors Reading When no message is sent

I'm trying to use a NIO server to read/write to a client for TCP connections. I've made a successful connection, and my initial message is sent to the server and correctly processed. It says that the server is sending a message back, but I'm not receiving any input on the client side. Also, after the server sends a message back, the application crashes saying that it was trying to read a null pointer (Line 127 server code).
It's important to note that I'm new to this concept and I don't really understand selectors. I've looked at tutorials, but contradictary messages have led me to be even more confused on the issue. If anyone has any good tutorials on this topic I'd be greatly appreciative.
Here's my code.
Client Main Activity Screen
package com.example.client;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.client.ServerService.Connect;
public class MainActivity extends Activity {
Button button;
TextView textView;
EditText editText;
EditText editTextps;
static Handler handler;
Connect connect=null;
Object myLock=new Object();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.button1);
textView=(TextView) findViewById(R.id.textView1);
editText=(EditText) findViewById(R.id.editText1);
editTextps=(EditText) findViewById(R.id.editText2);
handler=new Handler(){
#Override
public void handleMessage(Message msg) { //Handle code for receiving messages
super.handleMessage(msg);//when a message is received it's input is processed here
Bundle bundle=msg.getData();
if(bundle.getInt("int") == 2){
if(bundle.getInt("valid") == 1){
Intent i = new Intent();
i.setClassName("com.example.client",
"com.example.client.ReadyScreen");
startActivity(i);
}else{
alertMessage();
editText.setText("");
editTextps.setText("");
}
}
}
};
startService(new Intent(getBaseContext(), ServerService.class));
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String str=editText.getText().toString();
String strps=editTextps.getText().toString();
Message msg=Message.obtain();
Bundle bundle=new Bundle();
bundle.putString("name", str);
bundle.putString("password", strps);
msg.setData(bundle);
ServerService.threadHandler.sendMessage(msg);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void alertMessage() {
final android.app.AlertDialog.Builder show = new AlertDialog.Builder(this).setTitle("Error").setMessage("Wrong username/password").setNeutralButton("close", null);
show.show();
}
}
Server Service where I'm running the connection and IO
package com.example.client;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class ServerService extends Service {
Handler handler;
static MyHandle threadHandler;
Connect connect=null;
Object myLock=new Object();
static SocketChannel socketChannel=null;
public ByteBuffer sendBuffer=ByteBuffer.allocate(1024);
static ByteBuffer receiveBuffer=ByteBuffer.allocate(1024);
static Selector selector;
private static final String TAG = ServerService.class.getSimpleName();
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Log.d(TAG, "Started running the service");
System.out.println(TAG + "Started running the service");
(new Thread(new ReceivingThread())).start();
(new Thread(new SendingThread())).start();
return START_STICKY;
}
#Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
class Connect {
SocketChannel socketChannel=null;
public ByteBuffer sendBuffer=ByteBuffer.allocate(1024);
ByteBuffer receiveBuffer=ByteBuffer.allocate(1024);
Selector selector;
public Connect() {
try {
socketChannel=SocketChannel.open();
SocketAddress remoteAddress=new InetSocketAddress("192.168.2.17", 20001);
socketChannel.connect(remoteAddress);
socketChannel.configureBlocking(false);
selector=Selector.open();
socketChannel.register(selector, SelectionKey.OP_READ);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ReceivingThread implements Runnable{
#Override
public void run() {
Log.d(TAG, "Started running the receive thread");
connect=new Connect();
try {
while(true){
if(connect.selector.select()==0)
continue;
Play receivedMessage = new Play();
receivedMessage.play();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
public class SendingThread implements Runnable{
#Override
public void run() {
Log.d(TAG, "Started running the send thread");
Looper.prepare();
threadHandler=new MyHandle(Looper.myLooper());
Looper.loop();
}
}
class MyHandle extends Handler{
public MyHandle(){
}
public MyHandle(Looper looper){
super(looper);
}
public void handleMessage(Message msg){
String str=msg.getData().getString("name");
String strps=msg.getData().getString("password");
MyMessage message=new MyMessage();
message.setb((byte)1);
message.setUsername(str);
message.setPassword(strps);
try {
connect.sendBuffer.clear();
connect.sendBuffer.put(message.Message2Byte());
connect.sendBuffer.flip();
connect.socketChannel.write(connect.sendBuffer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The Server Code
package mytcp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
public class NioServer {
/**
* #param args
*/
private int port = 20001;
final makeFlagFalse timerFlag = new makeFlagFalse();
static makeFlagFalse loginLoopBoolean = new makeFlagFalse();
private static ByteBuffer sBuffer = ByteBuffer.allocate(1024);
private static ByteBuffer rBuffer = ByteBuffer.allocate(1024);
private static Map<SocketChannel, Integer> clientsMap = new HashMap<SocketChannel, Integer>();
private Selector selector = null;
private ServerSocketChannel serverSocketChannel = null;
private Object gate = new Object();
public NioServer(int port) {
this.port = port;
try {
init();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException, IOException {
final NioServer server = new NioServer(20001);
Thread accept = new Thread() {
public void run() {
server.accept();
}
};
accept.start();
while (loginLoopBoolean.flag == true)
server.loginService();
server.gamePlay(clientsMap);
}
public void init() throws IOException {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().setReuseAddress(true);
// serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(port));
System.out.println("服务器启动");
}
public void accept() {
while (true) {
try {
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println("receive the connection from "
+ socketChannel.socket().getInetAddress() + ":"
+ socketChannel.socket().getPort());
socketChannel.configureBlocking(false);
synchronized (gate) {
selector.wakeup();
socketChannel.register(selector, SelectionKey.OP_READ);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
System.out.println("Damn it");
}
}
}
public void loginService() throws InterruptedException {
synchronized (gate) {
}
try {
int n = selector.select();
if (n == 0){}
else{
Set<SelectionKey> selectionKeys = selector.selectedKeys();
for (SelectionKey key : selectionKeys) {
try {
if (key.isReadable()) {
handle_receive_login(key);
}
} catch (Exception e) {
try {
if (key != null) {
key.cancel();
key.channel().close();
}
} catch (Exception ex) {
e.printStackTrace();
}
}
}
selectionKeys.clear();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void handle_receive_login(SelectionKey key) {
SocketChannel socketChannel = null;
ServerMessage message = null;
ServerMessage sendMessage = new ServerMessage();
socketChannel = (SocketChannel) key.channel();
rBuffer.clear();
try {
int count = socketChannel.read(rBuffer);
if (count > 0) {
rBuffer.flip();
message = ServerMessage.byte2Message(rBuffer.array());
System.out.println("Receive from"+ socketChannel.socket().getInetAddress() + " : "+ message.getb());
switch(message.getb()){
case(1):
int valid = DB.idCheck(message.getUsername(),
message.getPassword());
sendMessage.setb((byte) 2);
sendMessage.setValid(valid);
sendMes sendMes = new sendMes(sendMessage, socketChannel);
sendMes.send();
break;
case(2):
break;
case (3):
if(timerFlag.flag){
if(message.getReady() == 1){
if(clientsMap.size() < 6){
clientsMap.put(socketChannel, clientsMap.size() + 1);
sendMessage.setb((byte) 3);
sendMessage.setReady(1);
sendMes sendMes1 = new sendMes(sendMessage, socketChannel);
sendMes1.send();
}
else{
sendMessage.setb((byte) 3);
sendMessage.setReady(0);
sendMes sendMes1 = new sendMes(sendMessage, socketChannel);
sendMes1.send();
}
Timer timer = new Timer();
System.out.println("flag is " + timerFlag.flag);
TimerTask task = new TimerTask(){
public void run(){
timerFlag.falsify();
System.out.println("flag now is " + timerFlag.flag);
}
};
timer.schedule(task, 20*1000);
}
}else{
sendMessage.setb((byte) -1); /*-1 implies that game is currently in progress*/
sendMes sendMes1 = new sendMes(sendMessage, socketChannel);
sendMes1.send();
}
break;
case (4):
if(timerFlag.flag == true){
sendMessage.setb((byte) -2); /*send message saying "waiting for other players*/
sendMes sendMes1 = new sendMes(sendMessage, socketChannel);
sendMes1.send();
}else{
loginLoopBoolean.falsify();
}
break;
}
}/*end of if(count=0)*/
} catch (Exception e) {
e.printStackTrace();
key.cancel();
try {
socketChannel.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void gamePlay(Map<SocketChannel, Integer> clientsMap) throws IOException, InterruptedException{
Dealer dealer = new Dealer();
dealer.createDeck();
ServerMessage sendMessage = new ServerMessage();
if(!clientsMap.isEmpty()){
Set<SocketChannel> clientSet = clientsMap.keySet();
Iterator<SocketChannel> iterator=clientSet.iterator();
SocketChannel currentPlayer;
while(iterator.hasNext()){
currentPlayer=iterator.next();
sendMessage.setb((byte) 4);
sendMessage.setCard1(dealer.dealCard(dealer.deck));
sendMessage.setCard2(dealer.dealCard(dealer.deck));
sendMes sendMes1 = new sendMes(sendMessage, currentPlayer);
sendMes1.send();
}
//send who's turn it is
loginService();
}
}
public static class makeFlagFalse{
boolean flag;
public makeFlagFalse() {
this.flag = true;
}
public void falsify(){
flag = false;
}
public void makeTrue(){
flag = true;
}
}
public class sendMes{
ServerMessage message;
SocketChannel currentPlayer;
sendMes(ServerMessage message,SocketChannel currentPlayer){
this.message = message;
this.currentPlayer=currentPlayer;
}
public void send() throws IOException{
sBuffer.clear();
sBuffer.put(message.Message2Byte());
sBuffer.flip();
currentPlayer.write(sBuffer);
}
}
}
I'm appreciative of any kind of help.
Thank you
private Object gate = new Object();
it should be volatile

Categories

Resources