I was searching Google and found a code in stackoverflow. I started using it but the line list.setAdapter(aa); is generating NullPointerException. How can I resolve it? Here is my MainActivity.java:
public class MainActivity extends Activity {
private static int DISCOVERY_REQUEST = 1;
private Handler handler = new Handler();
private ArrayList<BluetoothDevice> foundDevices;
private ArrayAdapter<BluetoothDevice> aa;
private ListView list;
private BluetoothAdapter bluetooth;
private BluetoothSocket socket;
private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configureBluetooth();
setupListView();
setupSearchButton();
setupListenButton();
}
private void configureBluetooth() {
bluetooth = BluetoothAdapter.getDefaultAdapter();
}
private void setupListenButton() {
Button listenButton = (Button) findViewById(R.id.button_listen);
listenButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Intent disc = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(disc, DISCOVERY_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DISCOVERY_REQUEST) {
boolean isDiscoverable = resultCode > 0;
if (isDiscoverable) {
String name = "bluetoothserver";
try {
final BluetoothServerSocket btserver = bluetooth
.listenUsingRfcommWithServiceRecord(name, uuid);
AsyncTask<Integer, Void, BluetoothSocket> acceptThread = new AsyncTask<Integer, Void, BluetoothSocket>() {
#Override
protected BluetoothSocket doInBackground(
Integer... params) {
try {
socket = btserver.accept(params[0] * 1000);
return socket;
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(BluetoothSocket result) {
if (result != null)
switchUI();
}
};
acceptThread.execute(resultCode);
} catch (IOException e) {
Log.d("BLUETOOTH", e.getMessage());
}
}
}
}
private void setupListView() {
aa = new ArrayAdapter<BluetoothDevice>(this,
android.R.layout.simple_list_item_1, foundDevices);
list = (ListView) findViewById(R.id.list_discovered);
list.setAdapter(aa); //the error comes from this line
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int index,
long arg3) {
AsyncTask<Integer, Void, Void> connectTask = new AsyncTask<Integer, Void, Void>() {
#Override
protected Void doInBackground(Integer... params) {
try {
BluetoothDevice device = foundDevices
.get(params[0]);
socket = device
.createRfcommSocketToServiceRecord(uuid);
socket.connect();
} catch (IOException e) {
Log.d("BLUETOOTH_CLIENT", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
switchUI();
}
};
connectTask.execute(index);
}
});
}
private void setupSearchButton() {
Button searchButton = (Button) findViewById(R.id.button_search);
searchButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
registerReceiver(discoveryResult, new IntentFilter(
BluetoothDevice.ACTION_FOUND));
if (!bluetooth.isDiscovering()) {
foundDevices.clear();
bluetooth.startDiscovery();
}
}
});
}
private void switchUI() {
final TextView messageText = (TextView) findViewById(R.id.text_messages);
final EditText textEntry = (EditText) findViewById(R.id.text_message);
messageText.setVisibility(View.VISIBLE);
list.setVisibility(View.GONE);
textEntry.setEnabled(true);
textEntry.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) {
sendMessage(socket, textEntry.getText().toString());
textEntry.setText("");
return true;
}
return false;
}
});
BluetoothSocketListener bsl = new BluetoothSocketListener(socket,
handler, messageText);
Thread messageListener = new Thread(bsl);
messageListener.start();
}
private void sendMessage(BluetoothSocket socket, String msg) {
OutputStream outStream;
try {
outStream = socket.getOutputStream();
byte[] byteString = (msg + " ").getBytes();
byteString[byteString.length - 1] = 0;
outStream.write(byteString);
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
BroadcastReceiver discoveryResult = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
BluetoothDevice remoteDevice;
remoteDevice = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (bluetooth.getBondedDevices().contains(remoteDevice)) {
foundDevices.add(remoteDevice);
aa.notifyDataSetChanged();
}
}
};
private class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket, Handler handler,
TextView textView) {
this.socket = socket;
this.textView = textView;
this.handler = handler;
}
public void run() {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead == bufferSize)
&& (buffer[bufferSize - 1] != 0)) {
message = message
+ new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message
+ new String(buffer, 0, bytesRead - 1);
handler.post(new MessagePoster(textView, message));
socket.getInputStream();
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
}
And the error is:
Caused by: java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:464)
at com.example.testbluetooth.MainActivity.setupListView(MainActivity.java:113)
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/text_message"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:enabled="false" />
<Button
android:id="#+id/button_search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/text_message"
android:text="Search for listener" />
<Button
android:id="#+id/button_listen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/button_search"
android:text="Listen for connection" />
<ListView
android:id="#+id/list_discovered"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/button_listen"
android:layout_alignParentTop="true" />
<TextView
android:id="#+id/text_messages"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/button_listen"
android:layout_alignParentTop="true"
android:visibility="gone" />
</RelativeLayout>
You have empty list, you are setting up array list before have list with devices.
Try to remove
setupListView() from onCreate()
and put it into place after list with devices is created.
You can try to do it in this way:
Initialize collection in your case just write private ArrayList<BluetoothDevice> foundDevices = new ArrayList<BluetoothDevice>();
When you get broadcast foundDevices.add(remoteDevice);
aa.addAll(foundDevices) and then call aa.notifyDataSetChanged();
References:
ArrayAdapter.AddAll()
Related
I'm trying to recieve/send data to arduino board using bluetooth, and I can connect to board from one activity. I know that I can make my other activities connect with bluetooth using service but I don't know how to make bluetooth as service. and i don't know how to send and recieve from it.
my Paired Devices code:
public class BTConnect extends AppCompatActivity {
private static final String TAG = "BTConnect";
ListView IdLista;
public static String EXTRA_DEVICE_ADDRESS = "device_address";
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_btconnect);
}
#Override
public void onResume()
{
super.onResume();
//---------------------------------
VerificarEstadoBT();
//
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.btconnect_nombre);
IdLista = (ListView)findViewById(R.id.Id2);
IdLista.setAdapter(mPairedDevicesArrayAdapter);
IdLista.setOnItemClickListener(mDeviceClickListener);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
if (pairedDevices.size() > 0)
{
for (BluetoothDevice device: pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView av, View v, int arg2, long arg3) {
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Intent i = new Intent(BTConnect.this, device.class);
i.putExtra(EXTRA_DEVICE_ADDRESS, address);
startActivity(i);
}
};
private void VerificarEstadoBT() {
mBtAdapter= BluetoothAdapter.getDefaultAdapter();
if(mBtAdapter==null) {
Toast.makeText(getBaseContext(), "the device can't connect to BT", Toast.LENGTH_SHORT).show();
} else {
if (mBtAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth Activation...");
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}}
And my first activity 'device' :
public class device extends AppCompatActivity {
Button IdEncender, IdApagar,IdDesconectar,IdReset;
ArrayList<String> addArray = new ArrayList<String>();
ListView show;
//-------------------------------------------
Handler bluetoothIn;
final int handlerState = 0;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder DataStringIN = new StringBuilder();
private ConnectedThread MyConexionBT;
// Identificador unico de servicio - SPP UUID
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String para la direccion MAC
private static String address = null;
//-------------------------------------------
#SuppressLint("HandlerLeak")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device);
IdEncender = (Button) findViewById(R.id.IdEncender);
IdApagar = (Button) findViewById(R.id.IdApagar);
IdDesconectar = (Button) findViewById(R.id.IdDisconectar);
show = (ListView) findViewById(R.id.LIST1) ;
IdReset=(Button)findViewById(R.id.IdReset);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
DataStringIN.append(readMessage);
int endOfLineIndex = DataStringIN.indexOf("#");
if (endOfLineIndex > 0) {
String dataInPrint = DataStringIN.substring(0, endOfLineIndex);
String newline = "\r\n";
DataStringIN.delete(0, DataStringIN.length());
//--List adapter--//
addArray.add(dataInPrint);
ArrayAdapter<String> adapter =new ArrayAdapter<String>(device.this, android.R.layout.simple_list_item_1, addArray);
show.setAdapter(adapter);
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
VerificarEstadoBT();
IdEncender.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
MyConexionBT.write("1");
}
});
IdApagar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MyConexionBT.write("0");
}
});
IdDesconectar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (btSocket!=null)
{
try {btSocket.close();}
catch (IOException e)
{ Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_SHORT).show();;}
}
finish();
}
});
configurebutton();
}
private void configurebutton() {
Button startbutton = (Button)findViewById(R.id.Start);
startbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(device.this,chart.class));
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
{
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
}
#Override
public void onResume()
{
super.onResume();
Intent intent = getIntent();
address = intent.getStringExtra(BTConnect.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try
{
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "fail", Toast.LENGTH_LONG).show();
}
try
{
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {}
}
MyConexionBT = new ConnectedThread(btSocket);
MyConexionBT.start();
}
#Override
public void onPause()
{
super.onPause();
try
{
btSocket.close();
} catch (IOException e2) {}
}
private void VerificarEstadoBT() {
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "error in bluetooth connection", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
public void savefile(String file, String text){
try {
FileOutputStream fos = openFileOutput(file, Context.MODE_APPEND);
fos.write(text.getBytes());
fos.close();
Toast.makeText(device.this, "saved!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(device.this,"error",Toast.LENGTH_LONG).show();
}
}
//Crea la clase que permite crear el evento de conexion
private class ConnectedThread extends Thread
{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket)
{
InputStream tmpIn = null;
OutputStream tmpOut = null;
try
{
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run()
{
byte[] buffer = new byte[256];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void write(String input)
{
try {
mmOutStream.write(input.getBytes());
}
catch (IOException e)
{
Toast.makeText(getBaseContext(), "fail to connect", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
If shortly move your connection/message_exchange logic to Thread/Runnable and start it from Service. You can exchange data between Service and Activity/Activities with BroadcastReceivers or Messenger. I also recommend you to use Bluetooth lib:
implementation 'me.aflak.libraries:bluetooth:1.3.4' this one already have inside thread so it is become easy to embed in your service.
Example code of service which use this lib and Messenger:
private ArrayList<Messenger> mClients = new ArrayList<>();
final private Messenger inComingMessenger = new Messenger(mIncomingHandler);
#SuppressLint("HandlerLeak")
final Handler mIncomingHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
Log.d(TAG, "handleMessage: new client connected. Total: " + mClients.size());
break;
case Constants.MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
Log.d(TAG, "handleMessage: client disconnected. Total: " + mClients.size());
break;
case Constants.MSG_YOUR_MESSAGE_TYPE:
String val = (String) msg.obj;
// stuff to do
break;
}
}
};
/**
* Send message to connected activities
*/
public void sendMessageToClients(int msgSignal, Object obj) {
if (mClients.size() == 0)
return;
sendMessage(mClients.get(0), Message.obtain(null, msgSignal, obj));
for (int i = 1; i < mClients.size(); i++) {
if (mClients.get(i) == null)
continue;
sendMessage(mClients.get(i), Message.obtain(null, msgSignal, obj));
}
}
/**
* Send message to binded activity
*/
private void sendMessage(Messenger msgr, Message msg) {
try {
msgr.send((msg));
} catch (RemoteException e) {
Log.e(TAG, "can't send message", e);
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.d(TAG, "onStartCommand");
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind");
return inComingMessenger.getBinder();
}
#Override
public void onCreate() {
super.onCreate();
bleDevices = new ArrayList<>();
if(bluetooth == null) {
bluetooth = new Bluetooth(this);
bluetooth.setBluetoothCallback(new BluetoothCallback() {
#Override
public void onBluetoothTurningOn() {}
#Override
public void onBluetoothOn() {}
#Override
public void onBluetoothTurningOff() {
bluetooth = null;
}
#Override
public void onBluetoothOff() { }
#Override
public void onUserDeniedActivation() {
// when using bluetooth.showEnableDialog()
// you will also have to call bluetooth.onActivityResult()
}
});
bluetooth.setDiscoveryCallback(new DiscoveryCallback() {
#Override public void onDiscoveryStarted() {
}
#Override public void onDiscoveryFinished() {
bleDevices.clear();
}
#Override public void onDeviceFound(BluetoothDevice device) {
if(bleDevices.indexOf(device)<0) {
bleDevices.add(device);
Log.d(TAG, "Found new device while scanning: "+device.getAddress());
sendMessageToClients(Constants.MSG_BLE_DEVICE_FOUND, device);
}
}
#Override public void onDevicePaired(BluetoothDevice device) {}
#Override public void onDeviceUnpaired(BluetoothDevice device) {}
#Override public void onError(String message) {
Log.e(TAG, "DiscoveryCallback onError "+message);
}
});
bluetooth.setDeviceCallback(new DeviceCallback() {
#Override public void onDeviceConnected(BluetoothDevice device) { }
#Override public void onDeviceDisconnected(BluetoothDevice device, String message) { }
#Override public void onMessage(String message) {
// Handle your message
yourHandleFunction(message.replaceAll(" ",""));
Log.d(TAG, message);
}
#Override public void onError(String message) {
Log.e(TAG, "DeviceCallback onError "+message);
}
#Override public void onConnectError(BluetoothDevice device, String message) { }
});
bluetooth.onStart();
}
connectToSavedDevice();
}
}
private void connectToSavedDevice() {
Log.d(TAG, "connectToSavedDevice state="+getState());
if(getState() != STATE_DISCONNECTED) return;
SharedPreferences pref = getSharedPreferences(App.TAG, 0);
String address = pref.getString(Constants.PREF_AUTO_CONNECT_TO_ADDRESS, null);
if(address == null) {
Log.d(TAG, "saved address==null start scan for devices");
scanDevices();
return;
}
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
if(device!=null) {
Log.d(TAG, "device found try to connect/bound, connect to Arduino");
bluetooth.connectToAddress(address,false);
}
}
In activity implement ServiceConnection interface:
protected synchronized void unbindService() {
if (!isBound()) {
return;
}
// lock object (prevents access to service while disconnecting)
synchronized (outComingMessenger) {
sendMessageToService(Message.obtain(null, Constants.MSG_UNREGISTER_CLIENT));
unbindService(this);
outComingMessenger = null;
}
}
protected void bindService() {
bindService(mServiceIntent, this, BIND_AUTO_CREATE);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
outComingMessenger = new Messenger(service);
final Message msg = Message.obtain(null, Constants.MSG_REGISTER_CLIENT);
msg.replyTo = inComingMessenger;
msg.obj = getClass().getSimpleName();
sendMessageToService(msg);
sendMessageToService(Constants.MSG_CHECK_IS_CONNECTION_READY);
}
#Override
public void onServiceDisconnected(ComponentName name) {
outComingMessenger = null;
bindService();
}
/**
* Send message to service
*/
protected void sendMessageToService(Message msg) {
if (!isBound()) {
return;
}
try {
msg.replyTo = inComingMessenger;
outComingMessenger.send(msg);
} catch (RemoteException e) {
}
}
/**
* Send simple message to connected service
* #param messageId
*/
protected void sendMessageToService(int messageId) {
sendMessageToService(Message.obtain(null, messageId));
}
/**
* Send simple message to connected service
* #param messageId
*/
protected void sendMessageToService(int messageId, Object obj) {
sendMessageToService(Message.obtain(null, messageId, obj));
}
/**
* Service is connected?
*/
protected final boolean isBound() {
return outComingMessenger != null;
}
#SuppressLint("HandlerLeak")
private final Handler mIncomingHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MSG_YOUR_MESSAGE:
int res = (int) msg.obj;
break;
case Constants.MSG_CONNECTION_READY:
isReady = (boolean) msg.obj;
if(isReady) {
// show toast or what you want to do with the UI
} else {
// do something else
}
break;
case Constants.MSG_BLE_DEVICE_FOUND:
BluetoothDevice device = (BluetoothDevice)msg.obj;
SharedPreferences pref = getSharedPreferences(App.TAG, 0);
String deviceAddress = pref.getString(Constants.PREF_AUTO_CONNECT_TO_ADDRESS, null);
break;
}
}
};
final private Messenger inComingMessenger = new Messenger(mIncomingHandler);
How do I accurately measure the data rate of the router by using UDP?
My reference is Wi-Fi SweetSpots it measures the data transfer rate of the router locally (not internet speed)
Here's my code now, I'm getting around 700mbs to 800mbs (which is not correct)
public class RouterTransferRateService extends DaggerService {
public static final String ACTION_NAME = "rounter.transter.data.service";
#Inject
WifiManager wifiManager;
#Inject
WirelessInfoProvider wirelessInfoProvider;
private final IBinder binder = new RouterTransferRateDataBinder();
private TimerTask taskReceive;
private Timer timerReceive;
private boolean isSending = false;
private boolean isReceiving = false;
private final int BUF_SIZE = 65507;
private final int serverPort = 50001;
private final long MB = 1024L * 1024L;
private long oldBytes = 0;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
private void initializeTimerTask() {
taskReceive = new TimerTask() {
#Override
public void run() {
long currentBytes = TrafficStats.getUidRxBytes(myUid());
long bytesPerSec = currentBytes - oldBytes;
oldBytes = currentBytes;
Log.e("Data Rate?", (bytesPerSec / MB) + "Mbps");
}
};
new Thread(() -> {
try {
DatagramSocket senderSocket = new DatagramSocket();
senderSocket.setSendBufferSize(BUF_SIZE);
byte[] buf = new byte[BUF_SIZE];
InetAddress address = wirelessInfoProvider.getInetAddress();
new Random().nextBytes(buf);
while (isSending) {
try {
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, serverPort);
senderSocket.send(packet);
} catch (Exception e) {
}
}
senderSocket.disconnect();
senderSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
DatagramSocket receiverSocket = new DatagramSocket(serverPort);
receiverSocket.setReceiveBufferSize(BUF_SIZE);
byte[] buffer = new byte[BUF_SIZE];
DatagramPacket packet = new DatagramPacket(buffer, BUF_SIZE);
while (isReceiving) {
receiverSocket.receive(packet);
}
receiverSocket.disconnect();
receiverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
private void startTimer() {
isSending = true;
isReceiving = true;
initializeTimerTask();
timerReceive = new Timer();
timerReceive.schedule(taskReceive, 0, 1000);
}
private void stopTimer() {
isSending = false;
isReceiving = false;
if (timerReceive != null) {
timerReceive.cancel();
timerReceive = null;
}
}
#Override
public void onCreate() {
super.onCreate();
Log.e(getClass().getName(), "onCreate");
startTimer();
}
#Override
public void onDestroy() {
Log.e(getClass().getName(), "onDestroy");
stopTimer();
super.onDestroy();
}
#Override
public ComponentName startService(Intent service) {
return super.startService(service);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return binder;
}
public class RouterTransferRateDataBinder extends Binder {
public RouterTransferRateService getService() {
return RouterTransferRateService.this;
}
}
}
I'm trying to keep a socket open during lifecycle changes in a headless fragment with setRetainInstance(true); in onCreate. However, when my app comes back the following exception occurs.
E/Client: Receiving thread loop error
java.net.SocketException: Socket closed
at libcore.io.Posix.recvfromBytes(Native Method)
at libcore.io.Posix.recvfrom(Posix.java:189)
at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:250)
at libcore.io.IoBridge.recvfrom(IoBridge.java:549)
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:481)
at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
at java.io.InputStreamReader.read(InputStreamReader.java:233)
at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
at java.io.BufferedReader.readLine(BufferedReader.java:397)
at com.gm.popper_6.ConnectionFragment$Client$ReceivingThread.run(ConnectionFragment.java:183)
at java.lang.Thread.run(Thread.java:818)
Here's the code for the fragment
public class ConnectionFragment extends Fragment {
private InetAddress mGoAddress;
private int mGoPort;
private Client mClient;
private static final String TAG = "Connection";
private Server mServer;
private Socket mSocket;
private ConnectionFragmentListener listener;
private String mMessage;
public static ConnectionFragment newInstance(InetAddress address, int port){
Bundle bundle = new Bundle();
bundle.putSerializable("GoAddress", address);
bundle.putInt("GoPort", port);
ConnectionFragment fragment = new ConnectionFragment();
fragment.setArguments(bundle);
return fragment;
}
public interface ConnectionFragmentListener{
void onMessageRcvd(String message);
}
public void setConnectionFragmentListener(ConnectionFragmentListener listener){
this.listener = listener;
}
private void readBundle(Bundle bundle){
if (bundle != null){
mGoAddress = (InetAddress)bundle.getSerializable("GoAddress");
mGoPort = bundle.getInt("GoPort");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
readBundle(getArguments());
mGoAddress = (InetAddress) getArguments().getSerializable("GoAddress");
mGoPort = getArguments().getInt("GoPort");
mServer = new Server();
}
#Override
public void onStart() {
super.onStart();
}
// THE SERVER CLASS
private class Server{ //DECLARATION
ServerSocket mServerSocket = null;
Thread mThread = null;
public Server(){ //CONSTRUCTOR
mThread = new Thread(new ServerThread());
mThread.start();
}
public void tearDown(){
mThread.interrupt();
try {
mServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Error closing server socket");
}
}
class ServerThread implements Runnable{
#Override
public void run() {
//REMOVE OR COMMENT OUT FOR FINAL
//android.os.Debug.waitForDebugger();
try {
mServerSocket = new ServerSocket(mGoPort, 50, mGoAddress);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()){
try {
mSocket = mServerSocket.accept();
Log.d(TAG, "Connected");
if (mClient == null){
mClient = new Client();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
}
//THE CLIENT CLASS
private class Client { //DECLARATION
private final String CLIENT_TAG = "Client";
private Thread mSendThread;
private Thread mRecThread;
public Client() { //CONSTRUCTOR
Log.d(CLIENT_TAG, "Creating Client");
mSendThread = new Thread(new SendingThread());
mSendThread.start();
}
class SendingThread implements Runnable { //an inner class of Client
BlockingQueue<String> mMessageQueue;
private int QUEUE_CAPACITY = 10;
public SendingThread() {
mMessageQueue = new ArrayBlockingQueue<String>(QUEUE_CAPACITY);
}
#Override
public void run() {
mRecThread = new Thread(new ReceivingThread());
mRecThread.start();
while (true){
try {
String msg = mMessageQueue.take();
sendMessage(msg);
} catch (InterruptedException e) {
Log.d(CLIENT_TAG, "Sending loop interrupted, exiting");
}
}
}
} //closes SendingThread, an inner class of Client
class ReceivingThread implements Runnable{ //an inner class of Client
#Override
public void run() {
BufferedReader input;
try {
//android.os.Debug.waitForDebugger();
input = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
while (!Thread.currentThread().isInterrupted()){
String messageStr = null;
messageStr = input.readLine(); //Line 183
if (messageStr!= null){
Log.d(CLIENT_TAG, "Read from the stream: " + messageStr);
mMessage = messageStr;
updateMessages(false);
}
else{
Log.d(CLIENT_TAG, "The null!!!");
}
}
input.close();
} catch (IOException e) {
Log.e(CLIENT_TAG, "Receiving thread loop error", e);
e.printStackTrace();
}
} //closes run method
} //closes ReceivingThread, an inner class of Client
public void tearDown(){ //a method of Client
try {
getSocket().close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String msg){ //a method of Client
try {
Socket socket = getSocket(); //should return mSocket
if (socket == null) {
Log.d(CLIENT_TAG, "Socket is null");
} else if (socket.getOutputStream() == null) {
Log.d(CLIENT_TAG, "Socket output stream in null");
}
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(getSocket().getOutputStream())), true);
out.println(msg);
out.flush();
mMessage = msg;
updateMessages(true);
} catch (UnknownHostException e){
Log.d(CLIENT_TAG, "Unkown host", e);
} catch (IOException e) {
Log.d(CLIENT_TAG, "I/O exception", e);
} catch (Exception e){
Log.d(CLIENT_TAG, "Error 3", e);
}
Log.d(CLIENT_TAG, "Message sent: " + msg);
} //closes sendMessage, a method of the inner Client class
} //closes Client class, an inner class of Connection
private Socket getSocket() {
return mSocket;
}
public synchronized void updateMessages(boolean local){
Log.i(TAG, "Updating message: " + mMessage);
if (local){
mMessage = "me: " + mMessage;
}
else{
mMessage = "them: " + mMessage;
}
if (listener!= null){
listener.onMessageRcvd(mMessage);
}
} //closes updateMessages
public void sendMessage(String msg){ //CALL FROM MAIN ACTIVITY
if(mClient != null){ //TO SEND A STRING MESSAGE
mClient.sendMessage(msg);
}
}
public void tearDown(){
mServer.tearDown();
mClient.tearDown();
}
#Override
public void onDestroy() {
tearDown();
super.onDestroy();
}
} //closes class declaration
And here's the main activity
public class MainActivity extends Activity implements ChannelListener, DeviceActionListener,
ConnectionInfoListener, ConnectionFragment.ConnectionFragmentListener{
//CLASS DECLARATIONS
public static final String TAG = "Popper";
private WifiP2pManager manager;
private Boolean isWifiP2pEnabled = false;
ArrayList<Target> mTargets = new ArrayList<Target>(0);
Target mTarget;
TextView rcvd;
TextView ip;
EditText mssg;
String goAddress = "";
InetAddress goInetAddress;
int prefixedPort;
//declare and initialize an intent filter
private final IntentFilter intentFilter = new IntentFilter();
//private final IntentFilter serverFilter = new IntentFilter();
private Channel channel;
private BroadcastReceiver receiver = null;
private ConnectionInfoListener infoListener;
private Intent serverServiceIntent;
ConnectionFragment mConnection;
//????
public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
this.isWifiP2pEnabled = isWifiP2pEnabled;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//register app w/p2p framework with call to initialize
//channel is my apps connection to the p2p framework
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
receiver = new P2pReceiver(manager, channel, this);
rcvd = (TextView)findViewById(R.id.rcvd);
rcvd.setMovementMethod(new ScrollingMovementMethod());
//initialize filter and setup to listen for the following broadcast intents
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);
Resources res = getResources();
prefixedPort = res.getInteger(R.integer.GOport);
}
#Override
public void onMessageRcvd(String message) {
addLine(message);
}
#Override
protected void onResume() {
super.onResume();
receiver = new P2pReceiver(manager, channel, this);
registerReceiver(receiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_items, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.atn_direct_discover:
if (!isWifiP2pEnabled) {
NotificationToast.showToast(MainActivity.this, "Enable P2P!!!");
return true;
}
final TargetListFragment fragment = (TargetListFragment) getFragmentManager()
.findFragmentById(R.id.frag_list);
fragment.onInitiateDiscovery();
manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
NotificationToast.showToast(MainActivity.this, "Discovery initiated");
}
#Override
public void onFailure(int reason) {
NotificationToast.showToast(MainActivity.this, "Discovery failed");
}
});
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override //this is associated with ChannelListener
public void onChannelDisconnected() { //removal causes error.
}
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
goAddress = info.groupOwnerAddress.getHostAddress(); //this returns a string rep of add.
goInetAddress = info.groupOwnerAddress; //this returns actual inet add.
ip = (TextView) findViewById(R.id.ip);
mssg = (EditText) findViewById(R.id.mssg);
ip.setText(goAddress + ":" + "8080"); //display GO address and IP
startConnectionFragment();
}
//this override method is triggered by TargetListFragment's DeviceActionListener
#Override
public void connect(WifiP2pConfig config) {
manager.connect(channel, config, new ActionListener() {
#Override
public void onSuccess() {
//maybe use this to gray out and disable the listview object that connected
}
#Override
public void onFailure(int reason) {
}
});}
public void startConnectionFragment(){
mConnection = ConnectionFragment.newInstance(goInetAddress, prefixedPort);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(mConnection, "TAG_1");
ft.commit();
mConnection.setConnectionFragmentListener(this);
}
public void addLine(String line){
final String msg = line;
runOnUiThread(new Runnable(){
#Override
public void run() {
rcvd.append("\n" + msg);
}
});
}
#Override
public void onTargetListClick(Target target) {
mTarget = target;
}
public void stopServer() {
if(serverServiceIntent != null)
{
stopService(serverServiceIntent);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mConnection != null){
//mConnection.tearDown();
}
stopServer();
}
public void SendMessage(View v){
EditText txt = (EditText) this.findViewById(R.id.mssg);
String str = txt.getText().toString();
mConnection.sendMessage(str);
txt.getText().clear();
}
}
Could this have something to do with detaching when the app goes on pause or stop and not re-attaching when it comes back to life? Are there other things I should be considering?
Ultimately the app needs to keep communication open to about 5 or 6 devices over p2p. if there is a better strategy I'm open to suggestions. Thanks.
Update - So I've confirmed that both the onDestroy and onDetach methods of the fragment are firing when the main activity goes onStop. Since I have a method to close the sockets on death of the fragment they are getting closed. The big question now is how to keep the fragment alive?
You should maybe create a helper class that will open/close sockets on behalf of other classes, such as that fragment, that helper class won't be subjected to any life cycle events, and can be kept running as long as the Application process is alive
I created a XML file in my server. It contains title and link tags. I fetch the tags and display them as links in ListView. From there when the user clicks the link, then I'd like play the .pls file in the Radio Station app.
Here is my XML file:
<item>
<title> Kushi FM </title>
<link>http://108.163.197.114:8071/listen.pls</link>
</item>
I don't know how to play the link in next activity.
MainActivity:
public class MainActivity extends AppCompatActivity {
// All static variables
static final String URL1 = "http://servernmae.com/stations";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_LINK = "link";
URL url;
URLConnection urlConnection;
//Context context;
ListView listview;
int images=R.drawable.radio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// isNetworkAvailable(this);
listview = (ListView) findViewById(R.id.list);
if(isNetworkAvailable(this))
{
new GetData().execute();
}else {
Toast.makeText(getApplicationContext(), "Please Connect to Internet and Check Again ! Thanks)",
Toast.LENGTH_LONG).show();
}
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
Log.w("INTERNET:",String.valueOf(i));
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
Log.w("INTERNET:", "connected!");
return true;
}
}
}
}
return false;
}
class GetData extends AsyncTask<String, String, String> {
String xml = "error";
#Override
protected String doInBackground(String... params) {
try {
url = new URL(URL1);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isw);
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
xml = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
final ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
ArrayList<String> title= new ArrayList<>();
//title.add("");
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
Log.e("TAg1", getValue(e, KEY_TITLE));
//Log.e("TAg2", getValue(e, KEY_LINK));
map.put(KEY_TITLE, getValue(e, KEY_TITLE));
map.put(KEY_LINK, getValue(e, KEY_LINK));
menuItems.add(map);
title.add(getValue(e, KEY_TITLE));
}
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
}
String[] dataArr = new String[title.size()];
dataArr = title.toArray(dataArr );
CustomAdapter adapter = new CustomAdapter(getApplicationContext(), dataArr );
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//HashMap<String, String> selectedMap = menuItems.get(position);
HashMap<String,String> selectedMap= menuItems.get(position);
String urls = selectedMap.get(KEY_LINK);
Intent intent = new Intent(MainActivity.this, Service_Player.class);
intent.putExtra("url",urls);
startActivity(intent);
}
});
}
public final String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
Service_player.java
public class Service_Player extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service__player);
startService(new Intent(this, MediaPlayerService.class));
String url = getIntent().getStringExtra("url");
if (!TextUtils.isEmpty(url))
startMediaPlayer(url);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiverFromservice, new IntentFilter(MediaPlayerService.SERVICE_TO_ACTIVITY));
}
private String currentPlayerStatus = "N/A";
private BroadcastReceiver receiverFromservice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (MediaPlayerService.SERVICE_TO_ACTIVITY.equalsIgnoreCase(action)) {
/*
* To get current status of player
* */
currentPlayerStatus = intent.getStringExtra(MediaPlayerService.PLAYER_STATUS_KEY);
Log.e("Player Mode", "" + currentPlayerStatus);
}
}
};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiverFromservice);
}
public void startMediaPlayer(String url) {
Intent intent = new Intent();
intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE);
intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.PLAY_MEDIA_PLAYER);
intent.putExtra(MediaPlayerService.PLAYER_TRACK_URL, url);
sendBroadcast(intent);
}
MediaPlayerService.java
public class MediaPlayerService extends Service {
public static final String BROADCAST_TO_SERVICE = "com.mediaplayer.playerfunction";
public static final String SERVICE_TO_ACTIVITY = "com.mediaplayer.currentPlayerStatus";
public static final String PLAYER_FUNCTION_TYPE = "playerfunction";
public static final String PLAYER_TRACK_URL = "trackURL";
public static final int PLAY_MEDIA_PLAYER = 1;
public static final int PAUSE_MEDIA_PLAYER = 2;
public static final int RESUME_MEDIA_PLAYER = 3;
public static final int STOP_MEDIA_PLAYER = 4;
public static final int CHANGE_PLAYER_TRACK = 5;
public static final String PLAYER_STATUS_KEY = "PlayerCurrentStatus";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter intentFilter = new IntentFilter(BROADCAST_TO_SERVICE);
registerReceiver(playerReceiver, intentFilter);
if (mPlayer != null && mPlayer.isPlaying()) {
sendPlayerStatus("playing");
}
return START_STICKY;
}
private BroadcastReceiver playerReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BROADCAST_TO_SERVICE.equalsIgnoreCase(action)) {
String trackURL = intent.hasExtra(PLAYER_TRACK_URL) ? intent.getStringExtra(PLAYER_TRACK_URL) : "";
int function = intent.getIntExtra(PLAYER_FUNCTION_TYPE, 0);
switch (function) {
case CHANGE_PLAYER_TRACK:
changeTrack(trackURL);
break;
case STOP_MEDIA_PLAYER:
stopPlayer();
break;
case PLAY_MEDIA_PLAYER:
startMediaPlayer(trackURL);
break;
case PAUSE_MEDIA_PLAYER:
pausePlayer();
break;
case RESUME_MEDIA_PLAYER:
resumePlayer();
break;
}
}
}
};
private MediaPlayer mPlayer;
private void pausePlayer() {
if (mPlayer != null && mPlayer.isPlaying()) {
mPlayer.pause();
sendPlayerStatus("pause");
}
}
private void resumePlayer() {
if (mPlayer != null && !mPlayer.isPlaying()) {
mPlayer.start();
sendPlayerStatus("playing");
}
}
private void changeTrack(String url) {
stopPlayer();
startMediaPlayer(url);
}
private void stopPlayer() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
sendPlayerStatus("stopped");
}
}
public void startMediaPlayer(String url) {
if (TextUtils.isEmpty(url))
return;
if (mPlayer == null)
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(url);
mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (extra == MediaPlayer.MEDIA_ERROR_SERVER_DIED
|| extra == MediaPlayer.MEDIA_ERROR_MALFORMED) {
sendPlayerStatus("erroronplaying");
} else if (extra == MediaPlayer.MEDIA_ERROR_IO) {
sendPlayerStatus("erroronplaying");
return false;
}
return false;
}
});
mPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.e("onBufferingUpdate", "" + percent);
}
});
mPlayer.prepareAsync();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mPlayer.start();
sendPlayerStatus("playing");
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Log.e("onCompletion", "Yes");
sendPlayerStatus("completed");
}
});
mPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
return false;
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendPlayerStatus(String status) {
Intent intent = new Intent();
intent.setAction(SERVICE_TO_ACTIVITY);
intent.putExtra(PLAYER_STATUS_KEY, status);
sendBroadcast(intent);
}
Manifest.xml
<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Service_Player"
android:label="#string/title_activity_service__player" >
</activity>
<service android:name=".MediaPlayerService"></service>
</application>
I'll suggest you to use Service if you are creating app with MediaPlayer streaming or normal MediaPlayer. It will be easy to handle player background & centrally.
To use media player in Service you can use it with BroadCastReceiver or Bound Service as per your requirement.It would be good if MediaPlayer related service if you keep it running in foreground here in below code I have not handle for that please check the given link.
Here in sample code i have used BroadCast Receiver to send command from Activity to Service for MediaPlayer(like play ,pause, change track etc) and vice versa.
Now to get url which you are sending from Activity onItemClickListner ,you need to get from Intent.
String url = getIntent().getStringExtra("url");
PlayerScreen
public class PlayerScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
startService(new Intent(this, MediaPlayerService.class));
findViewById(R.id.btnChangeTrack).setOnClickListener(clickListener);
findViewById(R.id.btnStartMediaPlayer).setOnClickListener(clickListener);
findViewById(R.id.btnStopMediaPlayer).setOnClickListener(clickListener);
ToggleButton toggleButton = (ToggleButton) findViewById(R.id.togglePauseResume);
toggleButton.setOnCheckedChangeListener(checkedChangeListener);
/*
* To get url which is passing from the previous activity listitem click.
* If url which is pass from listitem click is not empty it will start player
* */
String url = getIntent().getStringExtra("url");
if (!TextUtils.isEmpty(url))
startMediaPlayer(url);
}
private ToggleButton.OnCheckedChangeListener checkedChangeListener = new ToggleButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
Intent intent = new Intent();
intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE);
intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.PAUSE_MEDIA_PLAYER);
sendBroadcast(intent);
} else {
Intent intent = new Intent();
intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE);
intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.RESUME_MEDIA_PLAYER);
sendBroadcast(intent);
}
}
};
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.btnChangeTrack:
intent = new Intent();
intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE);
intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.CHANGE_PLAYER_TRACK);
intent.putExtra(MediaPlayerService.PLAYER_TRACK_URL, "http://69.64.41.64:9938");
sendBroadcast(intent);
break;
case R.id.btnStartMediaPlayer:
startMediaPlayer("http://108.163.197.114:8071/listen.pls");
break;
case R.id.btnStopMediaPlayer:
intent = new Intent();
intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE);
intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.STOP_MEDIA_PLAYER);
sendBroadcast(intent);
break;
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiverFromservice, new IntentFilter(MediaPlayerService.SERVICE_TO_ACTIVITY));
}
private String currentPlayerStatus = "N/A";
private BroadcastReceiver receiverFromservice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (MediaPlayerService.SERVICE_TO_ACTIVITY.equalsIgnoreCase(action)) {
/*
* To get current status of player
* */
currentPlayerStatus = intent.getStringExtra(MediaPlayerService.PLAYER_STATUS_KEY);
Log.e("Player Mode", "" + currentPlayerStatus);
}
}
};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiverFromservice);
}
/**
* TO start media player.It will send broadcast to Service & from service player will start
*
* #param url
*/
public void startMediaPlayer(String url) {
Intent intent = new Intent();
intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE);
intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.PLAY_MEDIA_PLAYER);
intent.putExtra(MediaPlayerService.PLAYER_TRACK_URL, url);
sendBroadcast(intent);
}
}
MediaPlayerService
public class MediaPlayerService extends Service {
public static final String BROADCAST_TO_SERVICE = "com.mediaplayer.playerfunction";
public static final String SERVICE_TO_ACTIVITY = "com.mediaplayer.currentPlayerStatus";
public static final String PLAYER_FUNCTION_TYPE = "playerfunction";
public static final String PLAYER_TRACK_URL = "trackURL";
public static final int PLAY_MEDIA_PLAYER = 1;
public static final int PAUSE_MEDIA_PLAYER = 2;
public static final int RESUME_MEDIA_PLAYER = 3;
public static final int STOP_MEDIA_PLAYER = 4;
public static final int CHANGE_PLAYER_TRACK = 5;
public static final String PLAYER_STATUS_KEY = "PlayerCurrentStatus";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter intentFilter = new IntentFilter(BROADCAST_TO_SERVICE);
registerReceiver(playerReceiver, intentFilter);
if (mPlayer != null && mPlayer.isPlaying()) {
sendPlayerStatus("playing");
}
return START_STICKY;
}
private BroadcastReceiver playerReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BROADCAST_TO_SERVICE.equalsIgnoreCase(action)) {
String trackURL = intent.hasExtra(PLAYER_TRACK_URL) ? intent.getStringExtra(PLAYER_TRACK_URL) : "";
int function = intent.getIntExtra(PLAYER_FUNCTION_TYPE, 0);
switch (function) {
case CHANGE_PLAYER_TRACK:
changeTrack(trackURL);
break;
case STOP_MEDIA_PLAYER:
stopPlayer();
break;
case PLAY_MEDIA_PLAYER:
startMediaPlayer(trackURL);
break;
case PAUSE_MEDIA_PLAYER:
pausePlayer();
break;
case RESUME_MEDIA_PLAYER:
resumePlayer();
break;
}
}
}
};
private MediaPlayer mPlayer;
private void pausePlayer() {
if (mPlayer != null && mPlayer.isPlaying()) {
mPlayer.pause();
sendPlayerStatus("pause");
}
}
private void resumePlayer() {
if (mPlayer != null && !mPlayer.isPlaying()) {
mPlayer.start();
sendPlayerStatus("playing");
}
}
private void changeTrack(String url) {
stopPlayer();
startMediaPlayer(url);
}
private void stopPlayer() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
sendPlayerStatus("stopped");
}
}
public void startMediaPlayer(String url) {
if (TextUtils.isEmpty(url))
return;
if (mPlayer == null)
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(url);
mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (extra == MediaPlayer.MEDIA_ERROR_SERVER_DIED
|| extra == MediaPlayer.MEDIA_ERROR_MALFORMED) {
sendPlayerStatus("erroronplaying");
} else if (extra == MediaPlayer.MEDIA_ERROR_IO) {
sendPlayerStatus("erroronplaying");
return false;
}
return false;
}
});
mPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.e("onBufferingUpdate", "" + percent);
}
});
mPlayer.prepareAsync();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mPlayer.start();
sendPlayerStatus("playing");
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Log.e("onCompletion", "Yes");
sendPlayerStatus("completed");
}
});
mPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
return false;
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendPlayerStatus(String status) {
Intent intent = new Intent();
intent.setAction(SERVICE_TO_ACTIVITY);
intent.putExtra(PLAYER_STATUS_KEY, status);
sendBroadcast(intent);
}
}
player.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ab_tool"
android:text="Home" />
<Button
android:id="#+id/btnStartMediaPlayer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/section_label"
android:text="Start Player" />
<ToggleButton
android:id="#+id/togglePauseResume"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnStartMediaPlayer"
android:checked="true"
android:textOff="Resume"
android:textOn="Pause" />
<Button
android:id="#+id/btnChangeTrack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/togglePauseResume"
android:text="Chanage Track" />
<Button
android:id="#+id/btnStopMediaPlayer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnChangeTrack"
android:text="STOP" />
</RelativeLayout>
Manifest
<activity android:name=".PlayerScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MediaPlayerService"></service>
To get data from streaming url header data you can check this answer
For testing purpose here i have used two urls
UPDATE
PlayerActivity
public class PlayerScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
startService(new Intent(this, MediaPlayerService.class));
/*
* To get url which is passing from the previous activity listitem click.
* If url which is pass from listitem click is not empty it will start player
* */
String url = getIntent().getStringExtra("url");
if (!TextUtils.isEmpty(url))
startMediaPlayer(url);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiverFromservice, new IntentFilter(MediaPlayerService.SERVICE_TO_ACTIVITY));
}
private String currentPlayerStatus = "N/A";
private BroadcastReceiver receiverFromservice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (MediaPlayerService.SERVICE_TO_ACTIVITY.equalsIgnoreCase(action)) {
/*
* To get current status of player
* */
currentPlayerStatus = intent.getStringExtra(MediaPlayerService.PLAYER_STATUS_KEY);
Log.e("Player Mode", "" + currentPlayerStatus);
}
}
};
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiverFromservice);
}
/**
* TO start media player.It will send broadcast to Service & from service player will start
*
* #param url
*/
public void startMediaPlayer(String url) {
Intent intent = new Intent();
intent.setAction(MediaPlayerService.BROADCAST_TO_SERVICE);
intent.putExtra(MediaPlayerService.PLAYER_FUNCTION_TYPE, MediaPlayerService.PLAY_MEDIA_PLAYER);
intent.putExtra(MediaPlayerService.PLAYER_TRACK_URL, url);
sendBroadcast(intent);
}
}
let me know if anything.
MediaPlayer mp;
mp=MediaPlayer.create(getApplicationContext(),Uri.parse(url))
//Example url of .pls file http://50.xx.xxx.xx:xx40/)
mp.start();
mp.pause();
mp.release() (or mp.reset() as applicable)
I have a question about the progress bar. There is activity with question and answers. When user click on one of those answers. activity calls itself and generate new question with answers. In the header, I have progress bar, and the progress bar is full for N seconds. Every time the activity calls itself, the progress bar is full for N/2 seconds. I want to the progress bar to be full for N seconds, not for N/2. If you can help me, I'd be grateful. Problem is in the curiProgress function. Here is my code.
{
public class beze2 extends Activity{
String FILENAME = "HighScore";
FileOutputStream fos;
private boolean tocan = false;
private int c, progressStatus=400, id_odgovor, rezultat;
private myCountDownTimer timer;
private static int myProgress=400;
private ProgressBar progressBar;
private Handler myHandler=new Handler();
private TextView text, t;
private int[] b;
private String d, f, strin;
private ArrayList numbers;
private ArrayList<Pitanja> pitanja;
private ArrayList<Odgovor> odgovori;
private TestAdapter mDbHelper;
private Random r;
private LinearLayout ln;
LinearLayout.LayoutParams buttonParams;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getIntents();
initializeVariables();
dodajVrijednostiUb();
postaviPitanje();
postaviOdgovore();
curiProgress();
}
private void getIntents(){
Intent i = getIntent();
String reza = i.getStringExtra("REZULTAT");
strin = i.getStringExtra("EXTRA_M");
rezultat = Integer.parseInt(reza);
}
private void initializeVariables(){
progressBar=(ProgressBar)findViewById(R.id.myProgress);
text = (TextView) findViewById(R.id.vrijeme);
timer = new myCountDownTimer(20*1000,1*1000);
numbers = new ArrayList();
mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
mDbHelper.open();
pitanja = mDbHelper.getPitanje(Integer.parseInt(strin));
b = new int[pitanja.size()];
t = (TextView) findViewById(R.id.text_pitanja);
myProgress=400;
r = new Random();
progressBar.setMax(400);
ln = (LinearLayout) findViewById(R.id.layoutOdgovori);
buttonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
private void curiProgress(){
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(progressStatus>=0)
{
progressStatus=performTask();
myHandler.post(new Runnable()
{
public void run() {
progressBar.setProgress(progressStatus);
}
});
}
myHandler.post(new Runnable() {
#Override
public void run() {
progressStatus=0;
myProgress=0;
}
});
}
private int performTask()
{
try {
//---Do some task---
Thread.sleep(50);
} catch (InterruptedException e)
{
e.printStackTrace();
}
return --myProgress;
}
}).start();
}
private void dodajVrijednostiUb(){
for (int z=0;z<pitanja.size(); z++){
b[z] = pitanja.get(z).getId_pitanja();
numbers.add(b[z]);
}
}
private void postaviPitanje(){
while (!numbers.contains(c)){
c = r.nextInt(22) + 1;
}
for (int i=0;i<pitanja.size(); i++){
if (c==b[i]){
d = pitanja.get(i).getTekst_pitanja();
id_odgovor = pitanja.get(i).getOdgovor();
}
}
t.setText(d);
}
private void postaviOdgovore(){
odgovori = mDbHelper.getOdgovor(c);
for (int i = 0; i<odgovori.size(); i++){
final Button bt = new Button(this);
bt.setId(odgovori.get(i).getId_odgovor());
bt.setBackgroundResource(getResources().getIdentifier("buttoni", "drawable", getPackageName()));
final String text = odgovori.get(i).getOdgovor();
int l = odgovori.get(i).getId_odgovor();
final String s = Integer.toString(l);
bt.setText(text);
buttonParams.setMargins(20, 5, 20, 5);
bt.setLayoutParams(buttonParams);
ln.addView(bt);
bt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
f = Integer.toString(id_odgovor);
if (f.equals(s)){
tocan = true;
bt.setTextColor(Color.GREEN);
} else {
tocan = false;
bt.setTextColor(Color.RED);
Button newbutton = (Button) findViewById(id_odgovor);
newbutton.setTextColor(Color.GREEN);
}
timer.cancel();
if (tocan){
rezultat++;
timer.cancel();
Toast.makeText(beze2.this, "Tocan odgovor, vas score je " + Integer.toString(rezultat), Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), beze2.class);
i.putExtra("REZULTAT", Integer.toString(rezultat));
i.putExtra("EXTRA_M", strin);
startActivity(i);
}
else {
Toast.makeText(beze2.this, "Netocan odgovor, vas konacni score je " + Integer.toString(rezultat), Toast.LENGTH_SHORT).show();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
upisiDatoteku("Guest", rezultat);
Intent i = new Intent(beze2.this, MainActivity.class);
startActivity(i);
}
}
}
});
}
timer.start();
}
private void upisiDatoteku(String s, int rez){
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
String newOne = s + "\t" + Integer.toString(rez);
fos.write(newOne.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class myCountDownTimer extends CountDownTimer{
public myCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
text.setText("Time's up");
myHandler.post(new Runnable(){
#Override
public void run() {
try {
Thread.sleep(3000);
Intent i = new Intent(beze2.this, beze.class);
startActivity(i);
Toast.makeText(beze2.this, "Isteklo vam je vrijeme, Vas score je " + Integer.toString(rezultat), Toast.LENGTH_SHORT).show();
upisiDatoteku("Guest",rezultat);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onTick(long millisUntilFinished) {
int i = (int) millisUntilFinished / 1000;
text.setText(Integer.toString(i));
}
}