Schedule Asynctask - While? Service? Timer? - android

Ok, I got a Togglebutton that starts a service. The service starts a new Thread in onStartCommand. In this Thread an Asynctask is executed.
Now I want this Asynctask to be executed for example every 5 seconds. The Asynctask checks if the website is available.
-> if no, after 5 secs check again
-> if yes, show message and stop
Whats the best method with my already present code:
public class NotifiyService extends Service {
String savedsa;
Thread Th1;
boolean value;
final class TheThread implements Runnable{
int serviceID;
String savedsa1;
TheThread(int serviceID,String savedsa){
this.serviceID = serviceID;
this.savedsa1 = savedsa;
}
#Override
public void run() {
HttpTaskParams httpparams = new HttpTaskParams(value,savedsa1);
new HttpTask().execute(httpparams);
}
}
public NotifiyService() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences sharedPreferences7 = getSharedPreferences("Prefsa",MODE_WORLD_READABLE);
savedsa = sharedPreferences7.getString("keysa","");
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStarted)+ "\n" + savedsa,Toast.LENGTH_LONG).show();
Th1 = new Thread(new TheThread(startId,savedsa));
Th1.start();
return START_STICKY;
}
#Override
public void onDestroy() {
//super.onDestroy();
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
private static class HttpTaskParams{
boolean value;
String address;
HttpTaskParams(boolean value, String address){
this.value = value;
this.address = address;
}
}
private class HttpTask extends AsyncTask<HttpTaskParams,Void,Boolean>{
#Override
protected Boolean doInBackground(HttpTaskParams... params) {
boolean value = params[0].value;
String address = params[0].address;
try {
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
value = true;
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
return value;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(NotifiyService.this,"true",Toast.LENGTH_SHORT).show();
//Notification in Status Bar
NotificationCompat.Builder builder = new NotificationCompat.Builder(NotifiyService.this);
builder.setSmallIcon(R.drawable.dummy);
Intent intent = new Intent(NotifiyService.this, Main2Activity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(NotifiyService.this,0,intent,0);
builder.setContentIntent(pendingIntent);
builder.setLights(Color.YELLOW,600,600);
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.dummy));
builder.setContentTitle(getResources().getString(R.string.newNotify));
builder.setContentText(getResources().getString(R.string.newNotify2));
builder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
else{
Toast.makeText(NotifiyService.this,"false",Toast.LENGTH_SHORT).show();
}
}
}
}
EDIT:
#Override
public void run() {
ScheduledExecutorService checkreg = Executors.newScheduledThreadPool(1);
scheduledFuture = checkreg.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
HttpTaskParams httpparams = new HttpTaskParams(value, savedsa1);
new HttpTask().execute(httpparams);
}
}, 0, 20, TimeUnit.SECONDS);}
#Override
public void onDestroy() {
//super.onDestroy();
Th1.interrupt();
scheduledFuture.cancel(false);
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();
stopSelf();
}

I think a ScheduledExecutorService could help you.
Please check this answer.
Please let me know if this helps you.

try this /**
* Loads exchange rates form network periodically
* Returns results in broadcast message.
* Created by koss on 19.02.16.
* */
public class EcbEuropeService extends Service {
public static final String ECB_URL = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
public static final int UPDATE_PERIOD = 30000;
public static final int UPDATE_TICK = 1000;
public static final String NOTIFICATION = "koss.ru.oneclickrate.receiver";
public static final String EXTRA_CURRENCIES_MAP = "extra_currencies_map";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
getUrlData();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public Cubes getUrlData() {
(new AsyncTask<Object, Object, Cubes>() {
Map<CurrencyType, BigDecimal> result = new EnumMap<CurrencyType, BigDecimal>(CurrencyType.class);
#Override
protected Cubes doInBackground(Object... params) {
Cubes cubes = new Cubes();
InputStream is = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(ECB_URL);
urlConnection = (HttpURLConnection) url.openConnection();
is = urlConnection.getInputStream();
cubes = EcbEuropeResponseParser.parse(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(urlConnection!=null) IOUtils.close(urlConnection);
if(is!=null) IOUtils.closeQuietly(is);
return cubes;
}
}
#Override
protected void onPostExecute(Cubes map) {
super.onPostExecute(map);
sendBroadcastMessage(map);
startTimer();
}
}).execute();
return null;
}
/**
* Restarts timer
* */
public void startTimer() {
cdt.cancel();
cdt.start();
}
CountDownTimer cdt = new CountDownTimer(UPDATE_PERIOD, UPDATE_TICK) {
#Override
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
getUrlData();
}
};
private void sendBroadcastMessage(Cubes currenciesMap) {
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(EXTRA_CURRENCIES_MAP, currenciesMap);
sendBroadcast(intent);
}
}

Related

Measuring UDP speed

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;
}
}
}

Check for new chat messages at background, Android

I'm developing a application when which every 4,5 seconds the client checks whether the server responds "OK".
It's even working, But if I turn on/off the internet sometimes it stops working, it is inconsistent and I need to check the messages accurately.
And service stop like in example I gave and it re-operate outside the specified range of seconds (4.5)
I'm developing a chat, and I need to know this precisely, I need to be professional.
Start.java
public class Start extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
Intent serviceIntent = new Intent(getBaseContext(), BackExec.class);
getBaseContext().startService(serviceIntent);
}
#Override
protected void onResume()
{
super.onResume();
Intent serviceIntent = new Intent(getApplicationContext(), BackExec.class);
startService(serviceIntent);
}}
BackExec.java
public class BackExec extends Service {
static Timer t;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
String r = getData();
if(r != null){
if(r.equals("OK")){
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setSmallIcon(R.drawable.ic_ex);
b.setContentText("YOU HAVE NOTIFICATONS, CLICK.");
b.setContentTitle("TITLE APP:");
b.setOngoing(false);
b.setPriority(Notification.PRIORITY_MAX); //TALVEZ FUNCIONE
NotificationManager m = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
m.notify(0, b.build());
}
}
}
}, 1, 4500);
}
public int onStartCommand(Intent intent, int flags, int startId) {
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
String r = getData();
if(r != null){
if(r.equals("OK")){
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setSmallIcon(R.drawable.ic_ex);
b.setContentText("YOU HAVE NOTIFICATONS, CLICK.");
b.setContentTitle("TITLE APP:");
b.setOngoing(false);
b.setPriority(Notification.PRIORITY_MAX); //TALVEZ FUNCIONE
NotificationManager m = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
m.notify(0, b.build());
}
}
}
}, 1, 4500);
return START_STICKY;
}
public static String getData(){
URL site = null;
try {
site = new URL("http://192.168.0.10:8080/example/server.php");
URLConnection urlConn = site.openConnection();
urlConn.setRequestProperty("Cookie", CookieManager.getInstance().getCookie("http://192.168.0.10:8080/example"));
urlConn.setDoOutput(true);
PrintStream enviarInfos = new PrintStream(urlConn.getOutputStream());
enviarInfos.print("pac=pac");
urlConn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String inputLine;
String out = "";
while ((inputLine = in.readLine()) != null)
out = out + inputLine;
in.close();
return out;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
public void onStart(Intent intent, int startId) { } // TO DO
public IBinder onUnBind(Intent arg0) {
return null;
}
public void onStop() {}
public void onPause() {}
#Override
public void onDestroy() {}
#Override
public void onLowMemory() {} }

Not able to connect to REST API inside a service in some devices

I am using retrofit 1.9 in order to create and use connections with server , its working perfectly in app , but when i am trying to hit api in a service , it is returning me this error
"retrofit.RetrofitError: unexpected end of stream on Connection{, proxy=DIRECT# cipherSuite=none protocol=http/1.1} (recycle count=0)"
and only in some devices like for instance in my Xiaomi Redmi note 3.
Here is my code:-
public class TrackingService extends Service implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private String latitude = "", longitude = "";
private PrefsManager mPrefs;
int requestID = 42;
private int time = 120000;
private static final long SERVICE_INTERVAL = 60000;
private static final long SERVICE_FASTEST = 30000;
private static final long ONE_MIN = 1000;
private GoogleApiClient googleApiClient;
private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
private boolean canGetLocation = false;
private LocationRequest locationRequest;
private LocationManager locationManager;
private final String TAG = "MyAwesomeApp";
private Runnable runnable = new Runnable() {
#Override
public void run() {
updateLocation();
}
};
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
getHandler1().postDelayed(runnable, time);
return true;
}
});
private Handler handler1 = new Handler();
public Handler getHandler1() {
return handler1;
}
private NotificationCompat.Builder mBuilder;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
canGetLocation = !(!locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
}
};
private BroadcastReceiver receiverNetwork = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
handler.removeCallbacksAndMessages(null);
getHandler1().removeCallbacks(runnable);
time = 5000;
handler.sendMessage(new Message());
}
};
private static API REST_CLIENT;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
registerReceiver(receiverNetwork, new IntentFilter(Constants.NETWORK_BROADCAST));
registerReceiver(receiver, new IntentFilter(Constants.INTENT_LOCATION_SERVICE));
}
private void init() {
mPrefs = new PrefsManager(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationRequest.setInterval(SERVICE_INTERVAL);
locationRequest.setFastestInterval(SERVICE_FASTEST);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
canGetLocation = !(!locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
try {
googleApiClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
updateLocation();
}
#Override
public void onDestroy() {
Log.e(TAG, "GPSTrackerNew destroyed!");
googleApiClient.disconnect();
try {
unregisterReceiver(receiverNetwork);
unregisterReceiver(receiver);
} catch (Exception e) {
e.printStackTrace();
}
this.stopForeground(true);
super.onDestroy();
}
/**
* Update driver location for live tracking
*/
private void updateLocation() {
if (canGetLocation()) {
/*setNotification(this, getResources().getString(R.string.tracking));*/
if (!TextUtils.isEmpty(latitude) && !TextUtils.isEmpty(longitude)) {
get().updateLocation(mPrefs.getAccessToken(), latitude, longitude,
new Callback<PojoBase>() {
#Override
public void success(PojoBase pojoBase, Response response) {
try {
if (pojoBase.status == Constants.SUCCESS) {
time = 120000;
handler.removeCallbacksAndMessages(null);
getHandler1().removeCallbacks(runnable);
handler.sendMessage(new Message());
setNotification(TrackingService.this, getResources().getString(R.string.tracking));
} else if (pojoBase.status == Constants.LOGIN_EXPIRED) {
onDestroy();
}
} catch (Exception e) {
onDestroy();
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
time = 5000;
setNotification(TrackingService.this, getResources().getString(R.string.network_error));
handler.removeCallbacksAndMessages(null);
getHandler1().removeCallbacks(runnable);
handler.sendMessage(new Message());
}
});
} else {
time = 5000;
handler.removeCallbacksAndMessages(null);
getHandler1().removeCallbacks(runnable);
handler.sendMessage(new Message());
}
} else {
time = 5000;
handler.removeCallbacksAndMessages(null);
getHandler1().removeCallbacks(runnable);
handler.sendMessage(new Message());
setNotification(this, getResources().getString(R.string.not_able_to_fetch_location));
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
init();
return START_STICKY;
}
private void setNotification(Context context, String message) {
Intent intent = null;
intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, requestID,
intent, 0);
mBuilder = new NotificationCompat.Builder(context)
.setContentTitle(getResources().getString(R.string.app_name))
.setOngoing(true)
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent);
this.startForeground(requestID, mBuilder.build());
}
#Override
public void onConnected(#Nullable Bundle bundle) {
fusedLocationProviderApi.requestLocationUpdates(googleApiClient,
locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "GoogleApiClient connection has been suspend");
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.i("From service:", "Location received: " + location.toString());
canGetLocation = true;
latitude = String.valueOf(location.getLatitude());
longitude = String.valueOf(location.getLongitude());
} else {
canGetLocation = false;
}
}
public boolean canGetLocation() {
return canGetLocation;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "GoogleApiClient connection has been failed");
}
public static API get() {
if (REST_CLIENT == null) {
RestAdapter.Builder adapter = new RestAdapter.Builder()
.setClient(new OkClient(getClient()));
adapter.setLogLevel(RestAdapter.LogLevel.BASIC);
adapter.setEndpoint(Constants.ROOT);
RestAdapter mAdapter = adapter.build();
REST_CLIENT = mAdapter.create(API.class);
}
return REST_CLIENT;
}
private static OkHttpClient getClient() {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(30, TimeUnit.SECONDS);
return client;
}
}
Can anyone tell why is this happening ?
TIA
Try to use execute instead enqueue call.Services is already on different thread. So if you are making a network call on different thread you should run api on same thread.

NullPointerError: Cannot Connect to Server

I am attempting to connect to my XAMPP server and interact with the MySQL database with the classes below. However, the error notes that I receive a NullPointerException at the line:
result = imService.createNewGroup(newGroupName);
In the CreateGroup class. It should be noted that the CreateGroup class is also called right after a user inputs text into a Dialog and the service is started from there. I am fairly new to services and network connections, but is there something I'm missing that should allow to at least verify that the service is connected before trying to send the .createGroup command?
CreateGroup Class:
public class CreateGroup extends Activity {
private static final String SERVER_RES_RES_SIGN_UP_SUCCESFULL = "1";
private static final String SERVER_RES_SIGN_UP_USERNAME_CRASHED = "2";
private Manager imService;
private Handler handler = new Handler();
String newGroupName;
public ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(CreateGroup.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bindService(new Intent(CreateGroup.this, MessagingService.class),
mConnection, Context.BIND_AUTO_CREATE);
// Getting intent and info from the dialog
Intent i = getIntent();
Bundle extras = i.getExtras();
newGroupName = extras.getString("groupName");
Thread thread = new Thread() {
String result = new String();
#Override
public void run() {
// Send group name to the messaging
// service
try {
result = imService.createNewGroup(newGroupName);
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("problem", "The value of result is " + result.toString());
handler.post(new Runnable() {
#Override
public void run() {
if (result == null) {
Toast.makeText(getApplicationContext(),
"It's null, not working", Toast.LENGTH_LONG)
.show();
}
if (result != null
&& result
.equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) {
Toast.makeText(getApplicationContext(),
R.string.signup_successfull,
Toast.LENGTH_LONG).show();
// showDialog(SIGN_UP_SUCCESSFULL);
} else if (result != null
&& result
.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)) {
Toast.makeText(getApplicationContext(),
R.string.signup_username_crashed,
Toast.LENGTH_LONG).show();
// showDialog(SIGN_UP_USERNAME_CRASHED);
} else // if
// (result.equals(SERVER_RES_SIGN_UP_FAILED))
{
Toast.makeText(getApplicationContext(),
R.string.signup_failed, Toast.LENGTH_LONG)
.show();
// showDialog(SIGN_UP_FAILED);
}
}
});
}
};
thread.start();
}
Server Case for "createGroup" method:
case "createGroup":
$SQLtest = "insert into groups(groupName, uniqueGroup, createTime)
VALUES('TestGroup', 1234567891, NOW())";
error_log("$SQLtest", 3 , "error_log");
if($result = $db -> query($SQLtest))
{
$out = SUCCESSFUL;
}
else
{
$out = FAILED;
}
break;
Messaging Service and createGroup method:
public class MessagingService extends Service implements Manager, Updater {
// private NotificationManager mNM;
public static String USERNAME;
public static final String TAKE_MESSAGE = "Take_Message";
public static final String FRIEND_LIST_UPDATED = "Take Friend List";
public static final String MESSAGE_LIST_UPDATED = "Take Message List";
public ConnectivityManager conManager = null;
private final int UPDATE_TIME_PERIOD = 15000;
private String rawFriendList = new String();
private String rawMessageList = new String();
SocketerInterface socketOperator = new Socketer(this);
private final IBinder mBinder = new IMBinder();
private String username;
private String password;
private boolean authenticatedUser = false;
// timer to take the updated data from server
private Timer timer;
private StorageManipulater localstoragehandler;
private NotificationManager mNM;
public class IMBinder extends Binder {
public Manager getService() {
return MessagingService.this;
}
}
#Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
localstoragehandler = new StorageManipulater(this);
// Display a notification about us starting. We put an icon in the
// status bar.
// showNotification();
conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
new StorageManipulater(this);
// Timer is used to take the friendList info every UPDATE_TIME_PERIOD;
timer = new Timer();
Thread thread = new Thread() {
#Override
public void run() {
Random random = new Random();
int tryCount = 0;
while (socketOperator.startListening(10000 + random
.nextInt(20000)) == 0) {
tryCount++;
if (tryCount > 10) {
// if it can't listen a port after trying 10 times, give
// up...
break;
}
}
}
};
thread.start();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public String createNewGroup(String groupName) throws NullPointerException, UnsupportedEncodingException {
String params = "action=createGroup";
String result = socketOperator.sendHttpRequest(params);
return result;
}
}
Because your code has an inherent race condition. And an evil one.
Change to something like this:
public void onCreate(Bundle savedInstanceState) {
bindService(new Intent(CreateGroup.this, MessagingService.class),
mConnection, Context.BIND_AUTO_CREATE);
// but do not start thread here!
}
public ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
startCommunicationThread(); // <----------------------- only here can you start comm. thread
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(CreateGroup.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
void startCommunicationThread() {
Thread thread = new Thread() {
String result = new String();
#Override
public void run() {
try {
result = imService.createNewGroup(newGroupName);
..........
}
If you want your code to be even more secure, use a connection state field:
public ServiceConnection mConnection = new ServiceConnection() {
volatile boolean isConnected;
public void onServiceConnected(ComponentName className, IBinder service) {
isConnected = true; // <---------------------
imService = ((MessagingService.IMBinder) service).getService();
startCommunicationThread();
}
public void onServiceDisconnected(ComponentName className) {
isConnected = false; // <---------------
imService = null;
Toast.makeText(CreateGroup.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
And poll isConnected from within startCommunicationThread to make sure no sudden disconnects.
in my project MessagingService.IMBinder MessagingService gives error is there any java class that I should import.

Why does this service stop?

I have the following Service that is meant to check a web API.
The Implementation is meant to retry the HTTP request 5 times before issuing a notification.
Anyway it seems that the service simply stops after the first attempt.
Please what is going on???
public class CreditcheckService extends IntentService {
public CreditcheckService() {
super("CreditcheckService");
}
#Override
protected void onHandleIntent(Intent intent) {
String phone = "";
phone = intent.getStringExtra("phone");
checkcreditonline(phone);
Log.e("inizio il service","inizio il service");
}
private void checkcreditonline(final String phone) {
final Handler h = new Handler();
final JsonHttpResponseHandler jsonHttpResponseHandler = new JsonHttpResponseHandler() {
private int counter = 0;
#Override
public void onSuccess(JSONObject arg0) {
int cazzo=0;
cazzo++;
try {
String status = arg0.getString("credit");
} catch (JSONException e) {
e.printStackTrace();
}
try {
String status = arg0.getString("error");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable arg0) {
//IF FAILED SHOULD RETRY, BUT IT DOESN'T
if (counter < 5) {
//HERE THE SUCCESSIVE ATTEMPTS
h.postDelayed(new WebserviceRunnable(this, phone), 5000);
} else {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(CreditcheckService.this)
.setSmallIcon(R.drawable.icon)
.setContentTitle(getResources().getString(R.string.unable_to))
.setContentText(getResources().getString(R.string.please_connect));
mBuilder.setContentIntent(PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0));
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(999, mBuilder.build());
}
counter++;
}
};
h.post(new WebserviceRunnable(jsonHttpResponseHandler, phone));
}
private class WebserviceRunnable implements Runnable {
private JsonHttpResponseHandler jsonHttpResponseHandler;
private String email;
public WebserviceRunnable(
JsonHttpResponseHandler jsonHttpResponseHandler, String aEmail) {
this.jsonHttpResponseHandler = jsonHttpResponseHandler;
this.email = aEmail;
}
public void run() {
try {
WebServiceApi.get(
"rest/credit/get/" + URLEncoder.encode(email, "utf-8"),
null, jsonHttpResponseHandler);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
onHandleIntent in IntentService is asynchronous.
When onHandleIntent exits, the Service is stopped.
So don't post a message to a Handler, instead do it directly in checkcreditonline().

Categories

Resources