I had to establish a socket in ActivityA in normal and ready to send data,
but now I want to also be able to use the same socket connection to transmit the data in ActivityB.I have looked for information on the Internet, it seems can use the singleton.I studied for a few days, I still don't know how to start, even find some examples of exercises too, but still do not know how to use my original program.
I want to first establish between ActivityA and SERVER connection, and to pass a value to the SERVER, then press the button to switch to ActivityB, and also transmit values to SERVER
Give me some advice or teaching sites can be, so that I can continue to study it, thank you very much
Establish socket methods:
public class MainActivity extends Activity {
Button Btn_Wifi,Btn_Power,Btn_Flame;
Boolean connected=false;
Boolean powerstatus=false;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null ;
Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainView();
setListensers();
setButtonStatus();
}
private void mainView(){
Btn_Wifi = (Button) findViewById(R.id.Btn_Wifi);
Btn_Power = (Button) findViewById(R.id.Btn_Power);
Btn_Flame = (Button) findViewById(R.id.Btn_Flame);
}
private void setListensers(){
Btn_Wifi.setOnClickListener(BtnWifiOnClickListener);
Btn_Power.setOnClickListener(BtnPowerOnClickListener);
Btn_Flame.setOnClickListener(BtnFlameOnClickListener);
}
private void setButtonStatus(){
Btn_Power.setEnabled(false);
Btn_Flame.setEnabled(false);
}
Button.OnClickListener BtnWifiOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
if(!connected){
try {
socket = new Socket("IP", PORT);
dataOutputStream = new DataOutputStream(socket.getOutputStream());//and stream
changeConnectionStatus(true);//change the connection status
}catch (UnknownHostException e) {
changeConnectionStatus(false);
}catch (IOException e) {
changeConnectionStatus(false);
}
}else{
try {//try to close the socket
socket.close();
changeConnectionStatus(false);//change the connection status
} catch (UnknownHostException e) {//catch and
changeConnectionStatus(false);
} catch (IOException e) {//catch and
changeConnectionStatus(false);
}
}
}
};
Button.OnClickListener BtnPowerOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
if(!powerstatus){
try {
byte[] pon ={(byte) 0x10,(byte) 0x10};
dataOutputStream.write(pon);
dataOutputStream.flush();
PowerStatus(true);
}catch(Exception obj){
PowerStatus(false);
}
}else{
try {
byte[] poff ={(byte) 0x11,(byte) 0x11};
dataOutputStream.write(poff); //writeBytes(String str)
dataOutputStream.flush();
PowerStatus(false);
}catch(Exception obj){
PowerStatus(true);
}
PowerStatus(false);
}
}
};
Button.OnClickListener BtnFlameOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, FlameActivity.class);
startActivity(intent);
}
};
public void changeConnectionStatus(Boolean isConnected) {
connected=isConnected;//change variable
if(isConnected){//if connection established
Btn_Wifi.setText("CONNECTED");
Btn_Power.setEnabled(true);
}else{
Btn_Wifi.setText("NOT WIFI");
Btn_Power.setText("POWER OFF");
Btn_Power.setEnabled(false);
PowerStatus(false);
}
}
public void PowerStatus(Boolean isPowerOn) {
powerstatus=isPowerOn;//change variable
if(isPowerOn){//if connection established
Btn_Power.setText("POWER ON");
Btn_Flame.setText("SET FLAME");
Btn_Flame.setEnabled(true);
}else{
Btn_Power.setText("POWER OFF");
Btn_Flame.setText("CANT SET FLAME");
Btn_Flame.setEnabled(false);
}
}
}
You can certainly use it by declaring,i.e: in MainActivity which creates socket connection,static YourSocketClass objSocket // which creates connection and to use it in another Activity just called it as follow i.e:MainActivity.objSocket.yourMethod(any_param). by declaring static you can access it.
public static CommunicationClient objCommunicationClient;
public boolean setConnection(final String ipAddress, final Context context,
final boolean isFromSearch) {
class EstablishConnection extends AsyncTask<Void, Void, Boolean> {
ProgressDialog objDialog;
#Override
protected void onPreExecute() {
objDialog = new ProgressDialog(context);
objDialog.setMessage(context.getResources().getString(
R.string.strConnecting));
objDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
objDialog.show();
objDialog.setCancelable(false);
objDialog.setCanceledOnTouchOutside(false);
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
boolean isConnected = false;
boolean isValid = false;
StrictMode.setThreadPolicy(policy);
objCommunicationClient = new CommunicationClient(ipAddress);
isSocketInitiated = objCommunicationClient.initSocket();
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
CommonUtils.SSID = info.getSSID();
if (!isSocketInitiated) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
getResources().getString(
R.string.strCantConnect),
Toast.LENGTH_LONG).show();
}
});
} else {
isConnected = true;
if (!isFromSearch) {
CommonUtils.IP = ipAddress;
try {
objCommunicationClient.sendRequest(context,
"<APP_SPECIFIC>");
} catch (Exception e) {
e.printStackTrace();
}
} else {
isValid = isFromSearch;
}
if (isValid) {
final Intent objIntentToGraph = new Intent(context,
GraphDataActivity.class);
objIntentToGraph
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(objIntentToGraph);
overridePendingTransition(
R.anim.slide_in_right,
R.anim.slide_out_left);
finish();
}
});
}
}
return isConnected;
}
#Override
protected void onPostExecute(Boolean result) {
try {
objDialog.cancel();
} catch (Exception err) {
err.printStackTrace();
}
super.onPostExecute(result);
}
}
boolean status = false;
try {
status = new EstablishConnection().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return status;
}
}
// and in my other Activity i called it as
MainActivity_HomePage.objCommunicationClient.sendRequest(
context, CommonUtils.STOP_COMMAND); //send request is method which send message to server.
Related
I am using this code for connecting my android app to XMPP server i.e Openfire Server with Smack API
public class MyXMPP {
private static final String DOMAIN = "localhost";
private static final String HOST = "192.168.1.2";
private static final int PORT = 9090;
private String userName ="";
private String passWord = "";
AbstractXMPPConnection connection ;
ChatManager chatmanager ;
Chat newChat;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private boolean connected;
private boolean isToasted;
private boolean chat_created;
private boolean loggedin;
Context c;
//Initialize
public void init(Context context,String userId,String pwd ) {
Log.i("XMPP", "Initializing!");
this.userName = userId;
this.passWord = pwd;
this.c=context;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
//configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
// Disconnect Function
public void disconnectConnection(){
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connectConnection()
{
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
//connection.setPacketReplyTimeout(30000);
connection.connect();
login();
connected = true;
} catch (IOException e) {
}
catch (SmackException e)
{
Log.v("errror",e.getMessage());
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}
public void sendMsg() {
if (connection.isConnected()== true) {
// Assume we've created an XMPPConnection name "connection"._
chatmanager = ChatManager.getInstanceFor(connection);
newChat = chatmanager.createChat("concurer#nimbuzz.com");
try {
newChat.sendMessage("Howdy!");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
public void login() {
try {
connection.login(userName, passWord);
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
// Toast.makeText(c,"Login successfully",Toast.LENGTH_LONG).show();
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
//Connection Listener to check connection state
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ConnectionClosedOn Error!"+arg0);
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
}
});
}
}
}
but getting an exception i.e "No response received within reply timeout. A timeout was 10000ms (~10s). Used filter: No filter used or filter was 'null'.".
If am I missing something in my code, please let me know.
I'm trying to make an app reading a string coming from a socket connection, but after a few hours the app stops talking (without exceptions). I'm sure the app is still running because the server sending the string continues to detect the response echo after sending it.
public class MainActivity extends AppCompatActivity {
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.ITALY);
}
}
});
Thread socketT = new Thread(new SocketThread());
socketT.start();
}
#Override
public void onDestroy() {
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
private class SocketThread extends Thread {
static final int socketPort = 3333;
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(socketPort);
try {
while(true) {
Socket clientSocket = serverSocket.accept();
try {
new ServerThread(clientSocket);
} catch(IOException e) {
clientSocket.close();
} }
}
catch (IOException e) {
}
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread extends Thread {
private int counter = 0;
private int id = ++counter;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ServerThread(Socket s) throws IOException {
socket = s;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
out = new PrintWriter(new BufferedWriter(osw), true);
start();
}
public void run() {
try {
while (true) {
String str = in.readLine();
textToSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
}
} catch (IOException e) {}
try {
socket.close();
} catch(IOException e) {}
}
}
}
}
TextToSpeech instance will be available after connect to system service, not after invoke constructor.
So, your plan need to edit like this:
Call TextToSpeech constructor.
Check your TextToSpeech instance is finish to connect to system service through TextToSpeech.OnInitListener.onInit().
Then, connect to your custom service.
Try this as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
int res = textToSpeech.setLanguage(Locale.ITALY);
if (res >= TextToSpeech.LANG_AVAILABLE) {
// TextToSpeech instance is available after connect to system service!
Thread socketT = new Thread(new SocketThread());
socketT.start();
}
}
}
});
// At this time, your TextToSpeech instance may be not available yet.
//Thread socketT = new Thread(new SocketThread());
//socketT.start();
}
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 am creating my socket program on my main activity on Android Studio. Now I want to separate the socket portion by creating another class that will be called by my main activity. Need help. This is some part of my codes:
public class MainActivity extends Activity {
private Socket client;
private Button Connect,Disconnect;
EditText editTextAddress;
private TextView textResponse;
private BufferedReader BufferIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Connect = (Button) findViewById(R.id.connect);
Disconnect = (Button) findViewById(R.id.disconnect);
editTextAddress = (EditText) findViewById(R.id.address);
textResponse = (TextView) findViewById(R.id.response);
Disconnect.setOnClickListener(DisconnectOnClickListener);
Connect.setOnClickListener(ConnectOnClickListener);
}
//Button Disconnect
OnClickListener DisconnectOnClickListener = new OnClickListener() {
public void onClick(View v) {
if(client !=null) {
Toast.makeText(getApplicationContext(), "disconnected", Toast.LENGTH_LONG).show();
try {
client.close();
} catch (IOException e) { /* failed */ }
}else{
Toast.makeText(getApplicationContext(), "socket not found", Toast.LENGTH_LONG).show();
}
}
};
//Button Connect
OnClickListener ConnectOnClickListener = new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"connected", Toast.LENGTH_LONG).show();
mConnectAndPoll.start();
}
};
private final Thread mConnectAndPoll = new Thread(new Runnable() {
String serverm = null;
#Override
public void run() {
try {
final String address = editTextAddress.getText().toString();
client = new Socket(address, 8080);
mBufferIn = new BufferedReader(
new InputStreamReader(client.getInputStream()));
while (mRun) {
serverm = mBufferIn.readLine();
if (serverm != null) {
System.out.println(serverm);
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
EDIT:
Write Thread code in separate class like:
MyThread
public class MyThread extends Thread{
String serverm = null;
String address;
Socket client;
Context context;
public MyThread (String address, Context context )
{
this.address = address;
this.context = context;
}
public void stopSocket()
{
if(client !=null)
{
Toast.makeText(context, "disconnected", Toast.LENGTH_LONG).show();
try {
client.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Toast.makeText(context, "socket not found", Toast.LENGTH_LONG).show();
}
}
#Override
public void run() {
try {
client = new Socket(address, 8080);
BufferedReader mBufferIn = new BufferedReader(
new InputStreamReader(client.getInputStream()));
while (mRun) {
serverm = mBufferIn.readLine();
if (serverm != null) {
System.out.println(serverm);
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MainActivity
public class MainActivity extends Activity {
private Button Connect,Disconnect;
EditText editTextAddress;
private TextView textResponse;
private BufferedReader BufferIn;
MyThread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Connect = (Button) findViewById(R.id.connect);
Disconnect = (Button) findViewById(R.id.disconnect);
editTextAddress = (EditText) findViewById(R.id.address);
textResponse = (TextView) findViewById(R.id.response);
Disconnect.setOnClickListener(DisconnectOnClickListener);
Connect.setOnClickListener(ConnectOnClickListener);
}
//Button Disconnect
OnClickListener DisconnectOnClickListener = new OnClickListener() {
public void onClick(View v) {
thread.stopSocket();
}
};
//Button Connect
OnClickListener ConnectOnClickListener = new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"connected", Toast.LENGTH_LONG).show();
thread = new MyThread(editTextAddress.getText().toString(), getApplicationContext());
thread.start();
}
};
}
I am getting this error
java.lang.NullPointerException at android.content.ContextWrapper.getPackageManager
when am trying to get list of all installed applications on the device.
I have a server that starts when my application is started, and the client pings the server and asks to get a list of installed applications. The Server then asks the getPackageManager() and gets all the installed applications.
But the getPackageManager throws a NullPointerException.
The Server is written in a java and is started from my android application.
Could someone please tell me what am missing and why I am getting this error?
Please find the code below
public class ApplicationRecognition extends Activity {
// android.os.Debug.waitForDebugger();
Button buttonStart, buttonStop;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
final SecurityModuleServer server = new SecurityModuleServer(5902);
server.start();
Toast.makeText(this, "Application Server is started", Toast.LENGTH_SHORT).show();
buttonStart.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startService(new Intent(getBaseContext(), AppReconService.class));
}});
buttonStop.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
stopService(new Intent(getBaseContext(), AppReconService.class));
}});
}
public String[] getInstalledApplications()
{
String[] appname =new String[10];
Intent mainIntent = new Intent(Intent.ACTION_MAIN,null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PackageManager manager = getPackageManager();
List<ResolveInfo> pkgAppsList = manager.queryIntentActivities(mainIntent, 0);
appname = new String[pkgAppsList.size()];
for(int i=0;i<pkgAppsList.size();i++)
{
appname[i]=pkgAppsList.get(i).activityInfo.packageName;
}
return appname;
}
}
the server side code
public class SecurityModuleServer implements Observer,Runnable
{
private int numberOfConnectedClient;
private Thread serverThread;
private ServerSocket serverSocket;
private volatile boolean isServerRunning;
public SecurityModuleServer(final int port)
{
numberOfConnectedClient = 0;
try
{
serverSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run()
{
System.out.println("SecurityModuleServer>> server thread started."); //$NON-NLS-1$
while(isServerRunning)
{
numberOfConnectedClient++;
try
{
SecurityModuleClientThread client = new SecurityModuleClientThread(serverSocket.accept(), numberOfConnectedClient);
client.addObserver(this);
client.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println("SecurityModuleServer>> server thread stopped."); //$NON-NLS-1$
}
synchronized public void start()
{
serverThread = new Thread(this);
isServerRunning = true;
serverThread.start();
}
synchronized public void stop()
{
isServerRunning = false;
}
public boolean isRunning()
{
return isServerRunning;
}
public static void main(String[] args)
{
SecurityModuleServer server = new SecurityModuleServer(5903);
server.start();
}
public void update(Observable o, Object arg)
{
numberOfConnectedClient--;
}
}
the client side code
public SecurityModuleClientThread(Socket socket, int numberOfClient)
{
clientSocket = socket;
numberOfConnectedClient = numberOfClient;
try
{
printOut = new PrintStream(clientSocket.getOutputStream());
readerIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
clientThread = new Thread(this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void run()
{
Looper.prepare();
String input = ""; //$NON-NLS-1$
System.out.println("SecurityModuleClientThread>> thread started for client."); //$NON-NLS-1$
if (numberOfConnectedClient <= MAX_ALLOWED_CLIENTS)
{
printOut.println(CMD+Answer_Open_Connection+SEPARATOR+M002);
while(isClientRunning)
{
try
{
input = readerIn.readLine();
System.out.println("Message received>> "+input); //$NON-NLS-1$
parseInputMessage(input);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M003);
stop();
}
System.out.println("SecurityModuleClientThread>> thread stopped for client."); //$NON-NLS-1$
}
private void parseInputMessage(final String input)
{
if (input.equalsIgnoreCase(CMD+Request_Close_Connection))
{
printOut.println(CMD+Answer_Close_Connection+SEPARATOR+M007);
stop();
}
else
{
String messages[] = input.split(SEPARATOR);
// Parse the command
switch(parseCommand(messages[0]))
{
case Request_Start_Application:
if(parseApplicationName(input) != null)
{
if(startAndroidApplication(parseApplicationName(input)))
{
// TODO
printOut.println(CMD+Answer_Start_Application);
startAndroidApplication(parseApplicationName(input));
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
break;
case Request_Stop_Application:
if(parseApplicationName(input) != null)
{
if (stopAndroidApplication(parseApplicationName(input)))
{
// TODO
printOut.println(CMD+Answer_Stop_Application);
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
}
else
{
printOut.println(CMD+Error+SEPARATOR+M004);
}
break;
case Request_Application_Installed:
String[] appnames = new String[provideInstalledApplication().length];
appnames = provideInstalledApplication();
for(int i=0;i<appnames.length;i++)
{
printOut.println(appnames[i]);
}
break;
case Request_Application_Running:
//TODO
break;
default:
printOut.println(CMD+Error+SEPARATOR+M008);
break;
}
}
}
private int parseCommand(String cmd)
{
if (cmd.length() == 6)
{
return Integer.parseInt(cmd.substring(3, 6));
}
else
{
return 0;
}
}
private String parseApplicationName(String message)
{
if (message.length() > 6)
{
// TODO
return message.substring(6, message.length());
}
else
{
return null;
}
}
public synchronized void start()
{
isClientRunning = true;
clientThread = new Thread(this);
clientThread.start();
}
public synchronized void stop()
{
printOut.close();
try
{
readerIn.close();
clientSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
isClientRunning = false;
setChanged();
notifyObservers();
}
}
public boolean isRunning()
{
return isClientRunning;
}
public String[] provideInstalledApplication()
{
String[] appnames = null;
ApplicationRecognition apprecon = new ApplicationRecognition();
appnames=new String[apprecon.getInstalledApplications().length];
appnames = apprecon.getInstalledApplications();
return appnames;
}
public String[] provideRunningApplication()
{
// TODO Auto-generated method stub
return null;
}
public boolean startAndroidApplication(String applicationName)
{
// TODO Auto-generated method stub
ApplicationRecognition apprecon = new ApplicationRecognition();
apprecon.startApplication(applicationName);
return false;
}
public boolean stopAndroidApplication(String applicationName)
{
// TODO Auto-generated method stub
return false;
}
}
The main part that is giving me trouble is in ApplicationRecognition class under method getInstalledApplications() in getPackageManager is null.
This method is called from the client side SecurityModuleClientThread class, provideInstalledApplication method.
Can someone please tell me where am I going wrong.