Connecting to server in background on boot - android

I'm trying to create a service that runs in the background and starts on device boot. The service is supposed to start an AsyncTask which waits for messages from a server.
BootReceiver class:
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "In boot receiver app", Toast.LENGTH_LONG).show();
context.startService(new Intent(context, AppService.class));
}
}
Service class:
public class AppService extends Service{
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
super.onCreate();
try {
Toast.makeText(this, "In service app", Toast.LENGTH_LONG).show();
String message = new ListenForUpdates().execute(getApplicationContext()).get();
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onDestroy(){
super.onDestroy();
}
}
AsyncTask class:
public class ListenForUpdates extends AsyncTask<Context, Void, String> {
private static final int portNumber = 12302;
private ServerSocket serverSocket;
private Socket socket;
private BufferedReader in;
private Context context;
#Override
protected String doInBackground(Context... c) {
String message = "";
context = c[0];
try {
message = connectAndListen();
in.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
return message;
}
private String connectAndListen() throws IOException {
serverSocket = new ServerSocket(portNumber);
String message;
while (true){
socket = serverSocket.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((message = in.readLine()) != null){
message = in.readLine();
break;
}
break;
}
return message;
}
}
Additions to androidManifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
...
<service
android:name=".connections.AppService"
android:theme="#style/AppTheme.CustomTheme">
</service>
<receiver android:name=".connections.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
Code on server side:
try {
Socket s = new Socket("10.0.2.2", 12302);
BufferedWriter b = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
b.write("Received update! \n");
b.flush();
b.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
When I try to send messages to the server, it times out as if the AsyncTask has not yet started (?). What am I doing wrong here?

Related

Android socket connect in background

What should I do to keep the server running and listening when the application is in the background?
I'm currently throwing an error: I can't make a connection because the target computer is actively refusing to connect.
I have server on android and client on pc/python.
anyone could explain I will be grateful.
Code with my server.
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 8080;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
if (msg == null) {
text.setText(msg);
}
else{
text.setText(msg);
createNotification();
}
}
}
void createNotification() {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Notification noti = new NotificationCompat.Builder(this)
.setContentTitle("NOTIFICATION")
.setContentText("NOTIFICATION")
.setTicker("NOTIFICATION")
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setLargeIcon(icon)
.setAutoCancel(true)
.setContentIntent(pIntent)
.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
}}
To perform background tasks in Android you should use Services.
A service for the Server would look like:
public class MyService extends Service {
public static final String START_SERVER = "startserver";
public static final String STOP_SERVER = "stopserver";
public static final int SERVERPORT = 8080;
Thread serverThread;
ServerSocket serverSocket;
public MyService() {
}
//called when the services starts
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//action set by setAction() in activity
String action = intent.getAction();
if (action.equals(START_SERVER)) {
//start your server thread from here
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
if (action.equals(STOP_SERVER)) {
//stop server
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException ignored) {}
}
}
//configures behaviour if service is killed by system, see documentation
return START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
class ServerThread implements Runnable {
public void run() {
Socket socket;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String read = input.readLine();
//update ui
//best way I found is to save the text somewhere and notify the MainActivity
//e.g. with a Broadcast
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In your Activity, you can start the Service by calling:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//will start the server
Intent startServer = new Intent(this, MyService.class);
startServer.setAction(MyService.START_SERVER);
startService(startServer);
//and stop using
Intent stopServer = new Intent(this, MyService.class);
stopServer.setAction(MyService.STOP_SERVER);
startService(stopServer);
}
also you have to declare the Internet permission in your AndroidManifest.xml. Add these to lines above of the tag:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Are you testing this on a local area network or through the internet(WAN)?
It must be taken into account that currently many mobile phone providers do not assign public IP addresses to the connected devices, they assign private IP and therefore the device can not act as a server due its ports are inaccessible from the WAN

runOnUiThread from service to Activity

I have a method "send()" that send values to the server and then get response 0 or 1 from the server. then i want to active a method that check if its 0 or 1 and then i want to active a method that on MainActivity that called from the service.
this is the service code
public class SendThreadCommunication extends Thread {
private final static String TAG = "SendThreadCommunication";
private final int READ_TIMEOUT = 100000;
private final int CONNECTION_TINEOUT = 100000;
private Looper myLooper;
private int mResponseCode;
private String mData = "";
private final ServerRequest req;
// private RegisterUser user;
private static String ans;
public SendThreadCommunication(ServerRequest req) {
this.req = req;
}
public String readWebData(InputStream stream) {
String line = "";
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return buffer.toString();
}
#Override
public void run() {
try {
send();
// evaluateDataAndRespondToFragment(mData);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void send() throws ClientProtocolException, IOException {
OutputStream mOutputStream = null;
BufferedWriter mWriter = null;
List<NameValuePair> mParameters = req.getParameters();
URL url = null;
HttpURLConnection connection = null;
try {
Looper.prepare();
url = new URL(req.returnRequestUrl());
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TINEOUT);
connection.setRequestMethod(Params.HTTP_REQUEST_METHOD_POST);
connection.setDoOutput(true);
connection.setDoInput(true);
mOutputStream = connection.getOutputStream();
mWriter = new BufferedWriter(new OutputStreamWriter(mOutputStream, Params.UTF8));
String sparams = URLEncodedUtils.format(mParameters, Params.UTF8);
mWriter.write(sparams);
mWriter.flush();
mResponseCode = connection.getResponseCode();
if (mResponseCode > 203) {
mData = readWebData(connection.getErrorStream());
//this.req.getResponse().notGoodServerEroorr();
} else {
mData = readWebData(connection.getInputStream());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) {
try {
if (mOutputStream != null)
mOutputStream.close();
if (mWriter != null)
mWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection.disconnect();
evaluateDataAndRespondToFragment(mData);
myLooper = Looper.myLooper();
Looper.loop();
myLooper.quit();
}
}
}
private void evaluateDataAndRespondToFragment(String mData) {
Listen lis = this.req.getResponse();
if (mData.equals("1"))
lis.good();
else
lis.notGood();
if (mData.equals("0"))
{
lis.userGcmNotRegistered();
}
}
}
this service code send to the server values and get response. the method "evaluateDataAndRespondToFragment" check if its 0 or 1 and then active the appropriate method. that method should trigger other method in the MainActivity.
i know that runOnUiThread handle this, but i dont know how to use it.
the method on the MainActivity change the UI.
this is the MainActivity code
public class MainActivity extends Activity implements SensorEventListener, Listen {
private BroadcastReceiver statusReceiver;
private IntentFilter mIntent;
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
SendValues sv;
int counter3 = 0;
int counter5 = 0;
int pastTime = 0;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void good() {
Toast.makeText(getApplication(), "successful transfer", Toast.LENGTH_LONG).show();
}
#Override
public void notGood() {
Toast.makeText(getApplication(), "UNsuccssful transfer", Toast.LENGTH_LONG).show();
}
#Override
public void userGcmNotRegistered() {
Toast.makeText(getApplication(), "There is some problem, please register again to the App", Toast.LENGTH_LONG).show();
}
}
Here it should active one of the methods "good","not good"....
i know that runOnUiThread handle it but i dont know how to use it and where.
if anyone could tell me what to do i will appreciate.
A service doesn't have a runOnUiThread method, but you can use intent instead of.
Simply,
Add a BroadcastReceiver to your activity,
Add receiver to your AndroidManifest.xml,
Send intent from your service.
MainActivity.java
public class MainActivity extends Activity implements SensorEventListener, Listen {
private BroadcastReceiver statusReceiver;
private IntentFilter mIntent;
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
SendValues sv;
int counter3 = 0;
int counter5 = 0;
int pastTime = 0;
private static final String TAG = "MainActivity";
statusReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch(intent.getIntExtra("status", -1) {
case 1:
good();
break;
case 2:
notGood();
break;
default:
userGcmNotRegistered();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(statusReceiver, new IntentFilter("com.yourpackage.yourapp.GET_STATUS_INTENT");
}
#Override
public void good() {
Toast.makeText(getApplication(), "successful transfer", Toast.LENGTH_LONG).show();
}
#Override
public void notGood() {
Toast.makeText(getApplication(), "UNsuccssful transfer", Toast.LENGTH_LONG).show();
}
#Override
public void userGcmNotRegistered() {
Toast.makeText(getApplication(), "There is some problem, please register again to the App", Toast.LENGTH_LONG).show();
}
}
A simple AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourpackage.yourapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.yourpackage.yourapp.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>
<receiver android:name="MainActivity">
<intent-filter>
<action android:name="com.yourpackage.yourapp.GET_STATUS_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
evaluateDataAndRespondToFragment method
private void evaluateDataAndRespondToFragment(String mData) {
Intent intent = new Intent("com.yourpackage.yourapp.GET_STATUS_INTENT");
intent.putExtra(status, mData);
sendBroadcast(intent);
}
}
Additionally you need to register/unregister within your activity's onResume/onPause methods.
A bit off topic; but, Beremaran's answer is correct, you can't get the main thread from a service. However, runOnUiThread is a very important concept to know and use, to avoid blocking up your main thread. Blocking your main thread will cause the system to kill your app.
Let say you have some networking tasks to do, and you know that it can take some time to do that. Therefore you start a new Thread to do the slow work.
new Thread(new Runnable() {
#Override
public void run() {
messageFromSlowStuff = doSomeSlowStuff();
};
}).start();
Now you might want to populate the UI with the new data messageFromSlowStuff, but you can't because it is only aloud from the main thread.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
myTextView.setText(messageFromSlowStuff)
}
});
If you are only updating a view as in the example above you can use View.post() an alternative to runOnUiThread.
myTextView.post(new Runnable() {
public void run() {
messageFromSlowStuff = doSomeSlowStuff();
myTextView.setText(messageFromSlowStuff);
}
});
Here's the docs regarding View.post(): "post reference"

Android - continuous socket write

I'm working on an application that receives data from a bluetooth sensor, and I need to pass that data to a server socket running on a local machine. The data received is about 40 messages per second.
First, first i tried to solve it by using a seprate AsyncTask for each write, opening the socket, writing the data and closing the socket, and it worked fine, but raised some perfomance issues, so i had to find another solution.
I wrote a service that keeps the socket connection alive, but when I try to write data to the socket, I keep getting a broken pipe exception for each write.
Here's the code for the service:
public class SocketService extends Service {
public static final String SERVERIP = "10.64.64.197";
public static final int SERVERPORT = 4444;
private DataOutputStream out;
private Socket socket;
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
SocketService getService() {
return SocketService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
Runnable connect = new connectSocket();
new Thread(connect).start();
}
public void sendMessage(byte[] message) {
try {
out.write(message);
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
class connectSocket implements Runnable {
#Override
public void run() {
try {
Log.e("connectSocket", "Connecting...");
socket = new Socket(SERVERIP, SERVERPORT);
try {
out = new DataOutputStream(socket.getOutputStream());
Log.e("connectSocket", "Done.");
} catch (Exception e) {
Log.e("connectSocket", "Error", e);
}
} catch (Exception e) {
Log.e("connectSocket", "Error", e);
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
socket = null;
}
And the code where I call the sendMessage method:
if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
try {
mSocketService.sendMessage(txValue);
} catch (Exception e) {
Log.e(TAG, "data_available");
}
}
I'm stuck on this for a while now, so any help would be appreciated!

Service to receive UDP packet

I've created a service in order to listen if I receive message from a server (PC). But it doesn't work and I don't know why. Someone can help me ?
I call my service in my main activity , in the increate() like this :
Intent intent = new Intent(this, UDPlisten.class);
startService(intent);
I don't know how I can retrieve the data sent by the PC in my main activity. Because I would like receive a notification when the server send a message to the app.
Service :
public class UDPlisten extends Service {
static String UDP_BROADCAST = "UDPBroadcast";
DatagramSocket socket;
private void listenAndWaitAndThrowIntent(int port) throws Exception {
byte[] recvBuf = new byte[15000];
if (socket == null || socket.isClosed()){
socket = new DatagramSocket(port);
socket.setBroadcast(true);
}
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
Log.e("UDP", "Waiting for UDP broadcast");
socket.receive(packet);
String message = new String(packet.getData()).trim();
Log.e("UDP", "message: " + message);
// broadcastIntent(senderIP, message);
//socket.close();
}
private void broadcastIntent(String message) {
Intent intent = new Intent(UDPlisten.UDP_BROADCAST);
intent.putExtra("message", message);
sendBroadcast(intent);
}
Thread UDPBroadcastThread;
void startListenForUDPBroadcast() {
UDPBroadcastThread = new Thread(new Runnable() {
public void run() {
try {
// InetAddress broadcastIP =InetAddress.getByName("10.0.2.16");
int port = 4000;
while (shouldRestartSocketListen) {
listenAndWaitAndThrowIntent(port);
}
//if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
} catch (Exception e) {
Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());
}
}
});
UDPBroadcastThread.start();
}
private Boolean shouldRestartSocketListen=true;
void stopListen() {
shouldRestartSocketListen = false;
socket.close();
}
#Override
public void onCreate() {
shouldRestartSocketListen = true;
startListenForUDPBroadcast();
Log.i("UDP", "Service started");
};
#Override
public void onDestroy() {
stopListen();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
shouldRestartSocketListen = true;
startListenForUDPBroadcast();
Log.i("UDP", "Service started");
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
Thanks in advance !

Android Service exits leaving imp. data open

I am facing a grave problem. Inside a service I am opening Wifi connection and closing it after my task completes. Since, a service exits at any point i face a problem wherein the connection opens and remains open.
Is there a way i can handle this as i am using START_STICKY or i will have to handle it programmatically only?
EDIT : Can i share my intent information across couple of receivers (BroadcastReceiver). For example, I will write another receiver for action android.net.wifi.wifi_state_changed and my existing receiver is for android.intent.action.PHONE_STATE.
IF that can be achieved i can do something about it.
EDIT2 : My code is as follows:
public class CallReceiver extends BroadcastReceiver {
private static final String LOG_TAG = "CallReceiver";
private static final String CALL_ACTION = "android.intent.action.PHONE_STATE";
#Override
public void onReceive(Context context, Intent callIntent)
{
Log.d(LOG_TAG, "----------------Inside onReceive of CallReceiver----------------");
if (callIntent.getAction().equals(CALL_ACTION))
{
try
{
Intent myIntent = new Intent(context, MyService.class);
context.startService(myIntent);
}
catch (Exception e)
{
e.printStackTrace();
Log.d(LOG_TAG,"----------------Exception occured while starting service----------------");
}
}
}
}
public class MyService extends Service {
private Context context;
private static final String LOG_TAG = "MyService";
private Thread thread = null;
public MyService()
{
super();
Log.d(LOG_TAG, "----------------Inside Email Service constructor----------------");
}
public int onStartCommand(Intent myIntent, int flags, int startId)
{
Log.d(LOG_TAG, "----------------Email Service Command Started----------------");
try
{
context = getApplicationContext();
if(thread == null || !thread.isAlive())
{
thread = new Thread(new MyRunnable("Email Sender", myIntent));
thread.start();
}
}
catch (Exception e)
{
e.printStackTrace();
Log.d(LOG_TAG,
"----------------Exception occured in Email Service onStartCommand----------------");
}
return START_REDELIVER_INTENT;
}
class MyRunnable implements Runnable {
String name;
Intent myIntent;
public MyRunnable(String name, Intent myIntent) {
this.name = name;
this.myIntent = myIntent;
}
#Override
public void run()
{
try
{
doStuff(emailIntent);
}
catch (NumberFormatException e)
{
e.printStackTrace();
Log.d(LOG_TAG, e.getMessage());
}
catch (InterruptedException e)
{
e.printStackTrace();
Log.d(LOG_TAG, e.getMessage());
}
catch (Exception e)
{
e.printStackTrace();
Log.d(LOG_TAG, e.getMessage());
}
finally
{
stopSelf();
}
}
}
private void doStuff(Intent emailIntent) throws InterruptedException, Exception
{
if (context != null)
{
boolean isWifiConnection = false;
try
{
// Check if WiFi connection is available ,if yes try opening it;
// Attempt to open WiFi connection
isWifiConnection = Utility.isEnableWifiSuccessful(getApplicationContext());
Log.d(LOG_TAG, "----------------Wifi conn enabled = " + isWifiConnection
+ "----------------");
if (isWifiConnection)
{
// Do more stuff
}
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
// Code never reaches here !! Somehow, the service stops and by
// the time the service stops,
// WiFi has been enabled
try
{
if (isWifiConnection)
{
Utility.isDisableWifiSuccessful(getApplicationContext());
}
}
catch (Exception e)
{
e.printStackTrace();
Log.d(LOG_TAG,
"----------------Error occured while closing network connections----------------");
}
}
}
else
{
Log.d(LOG_TAG, "----------------Context is null----------------");
}
}
#Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
return null;
}
}
Now, if i have another receiver as NetworkReceiver
public class NetworkReceiver extends BroadcastReceiver {
private static final String ACTION = "android.net.wifi.WIFI_STATE_CHANGED";
private static final String LOG_TAG = "NetworkReceiver";
#Override
public void onReceive(Context context, Intent networkIntent)
{
if(networkIntent.getAction().equals(ACTION))
{
Log.d(LOG_TAG, "----------------Inside Network Receiver----------------");
//Do something which will keep track who has opened the WiFi connection
}
}
}
then can myIntent and networkIntent share information and can MySerivce read that information.
Any help would be really grateful.
Service exits when the memory is too low, since you are already using START_STICKY, the service will be restarted once the memory resources are available. I beleive you might need to check if the connection is opened and you are done with the task, then you have stop the service by using stopSelf().
Hope this helps.
Thanks,
Ramesh

Categories

Resources