I'm making a Cloud Service that uses a standard HTTP get to get commands. I use a service (extending class IntentService as opposed to Service) to keep things in sync. I have the checking going on in a TimerTask firing off every 3 seconds. The problem is that when the user goes back to the activity to turn it off if they want, they press a toggle button. How do I tell the TimerTask (or the IntentService running a timer task) to stop and start it?
The service itself is getting destroyed after it handles the intent and creates the task, so would a Service be more appropriate for this than an IntentService? Even if thats the case, the question about stopping and starting the TimerTask remains.
Here's the code to the intentservice:
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.widget.*;
public class syncservice extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public syncservice() {
super("syncservice");
}
public static final String PREFS_NAME = "prefcs";
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final String uid = intent.getExtras().get("uid").toString();
final String dvname = intent.getExtras().get("dvname").toString();
final long period = intent.getExtras().getLong("period");
final Context ctx = getApplicationContext();
final Toast toast = Toast.makeText(ctx,"An error occured with the service. It will automatically turn off.", 0);
final Handler handler = new Handler();
TimerTask timertask = new TimerTask () {
#Override
public void run() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("doservice", false)) {
String command = netread("url here");
//TODO Parse command from Pulling
if (command.contains("<")) {
//TODO what to do if an error occurred (exceptions already caught
Runnable showerrormessage = new Runnable() {
public void run() {
toast.makeText(ctx,"new text",0);
toast.show();
}
};
handler.post(showerrormessage);
}
}
}
};
Timer timer = new Timer();
timer.schedule(timertask,0,period);
return super.onStartCommand(intent,flags,startId);
}
public void onDestroy() {
Toast.makeText(getApplicationContext(), "The Service has died", Toast.LENGTH_SHORT).show();
return;
}
#Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(getApplicationContext(), "Intent Handled", 0).show();
}
public final String netread(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
return page;
} catch (ClientProtocolException e) {
//Toast.makeText(getApplicationContext(),"Client Protocol Exception! Try again.",0).show();
return "<";
} catch (IOException e) {
//Toast.makeText(getApplicationContext(),"IO Exception! Make sure you are connected to the internet and try again.", 0).show();
return "<";
}
}
}
Thanks a bunch for helping me out!
For what you're trying to do, Handler may be more useful. That link BTW shows also how to stop it from the UI.
Related
I'm trying to to build an app which has to run in the background. So for this I'm using the ForegroundService, but when I write "this" in the CommunicateViewModel class, it gets underlined and show me:
"Cannot resolve constructor
'Intent(com.harrysoft.androidbluetoothserial.demoapp.CommunicateViewModel,
java.lang.Class<com.harrysoft.androidbluetoothserial.demoapp.TimeService>)'"
and at the next this:
"Wrong 1st argument type. Found:
'com.harrysoft.androidbluetoothserial.demoapp.CommunicateViewModel',
required: 'android.content.Context' less... Inspection info:
startForegroundService (android.content.Context, Intent) in
ContextCompat cannot be applied to
(com.harrysoft.androidbluetoothserial.demoapp.CommunicateViewModel,
Intent) "
How can I solve this problem?
CommunicateViewModel:
package com.harrysoft.androidbluetoothserial.demoapp;
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.harrysoft.androidbluetoothserial.BluetoothManager;
import com.harrysoft.androidbluetoothserial.SimpleBluetoothDeviceInterface;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
public class CommunicateViewModel extends AndroidViewModel {
// A CompositeDisposable that keeps track of all of our asynchronous tasks
private CompositeDisposable compositeDisposable = new CompositeDisposable();
// Our BluetoothManager!
private BluetoothManager bluetoothManager;
// Our Bluetooth Device! When disconnected it is null, so make sure we know that we need to deal with it potentially being null
#Nullable
private SimpleBluetoothDeviceInterface deviceInterface;
// The messages feed that the activity sees
private MutableLiveData<String> messagesData = new MutableLiveData<>();
// The connection status that the activity sees
private MutableLiveData<ConnectionStatus> connectionStatusData = new MutableLiveData<>();
// The device name that the activity sees
private MutableLiveData<String> deviceNameData = new MutableLiveData<>();
// The message in the message box that the activity sees
private MutableLiveData<String> messageData = new MutableLiveData<>();
// Our modifiable record of the conversation
private StringBuilder messages = new StringBuilder();
// Our configuration
private String deviceName;
private String mac;
// A variable to help us not double-connect
private boolean connectionAttemptedOrMade = false;
// A variable to help us not setup twice
private boolean viewModelSetup = false;
// Called by the system, this is just a constructor that matches AndroidViewModel.
public CommunicateViewModel(#NonNull Application application) {
super(application);
}
// Called in the activity's onCreate(). Checks if it has been called before, and if not, sets up the data.
// Returns true if everything went okay, or false if there was an error and therefore the activity should finish.
public boolean setupViewModel(String deviceName, String mac) {
// Check we haven't already been called
if (!viewModelSetup) {
viewModelSetup = true;
// Setup our BluetoothManager
bluetoothManager = BluetoothManager.getInstance();
if (bluetoothManager == null) {
// Bluetooth unavailable on this device :( tell the user
toast(R.string.bluetooth_unavailable);
// Tell the activity there was an error and to close
return false;
}
// Remember the configuration
this.deviceName = deviceName;
this.mac = mac;
// Tell the activity the device name so it can set the title
deviceNameData.postValue(deviceName);
// Tell the activity we are disconnected.
connectionStatusData.postValue(ConnectionStatus.DISCONNECTED);
}
// If we got this far, nothing went wrong, so return true
return true;
}
// Called when the user presses the connect button
public void toconnect(){
Intent serviceIntent = new Intent(this, TimeService.class);
serviceIntent.putExtra("inputExtra", "this can be set invissable");
ContextCompat.startForegroundService(this, serviceIntent);
connect();
}
public void connect() {
// Check we are not already connecting or connected
if (!connectionAttemptedOrMade) {
// Connect asynchronously
compositeDisposable.add(bluetoothManager.openSerialDevice(mac)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(device -> onConnected(device.toSimpleDeviceInterface()), t -> {
toast(R.string.connection_failed);
connectionAttemptedOrMade = false;
connectionStatusData.postValue(ConnectionStatus.DISCONNECTED);
}));
// Remember that we made a connection attempt.
connectionAttemptedOrMade = true;
// Tell the activity that we are connecting.
connectionStatusData.postValue(ConnectionStatus.CONNECTING);
}
}
// Called when the user presses the disconnect button
public void disconnect() {
// Check we were connected
if (connectionAttemptedOrMade && deviceInterface != null) {
connectionAttemptedOrMade = false;
// Use the library to close the connection
bluetoothManager.closeDevice(deviceInterface);
// Set it to null so no one tries to use it
deviceInterface = null;
// Tell the activity we are disconnected
connectionStatusData.postValue(ConnectionStatus.DISCONNECTED);
}
}
// Called once the library connects a bluetooth device
private void onConnected(SimpleBluetoothDeviceInterface deviceInterface) {
this.deviceInterface = deviceInterface;
if (this.deviceInterface != null) {
// We have a device! Tell the activity we are connected.
connectionStatusData.postValue(ConnectionStatus.CONNECTED);
// Setup the listeners for the interface
this.deviceInterface.setListeners(this::onMessageReceived, this::onMessageSent, t -> toast(R.string.message_send_error));
// Tell the user we are connected.
toast(R.string.connected);
// Reset the conversation
messages = new StringBuilder();
messagesData.postValue(messages.toString());
} else {
// deviceInterface was null, so the connection failed
toast(R.string.connection_failed);
connectionStatusData.postValue(ConnectionStatus.DISCONNECTED);
}
getCurrentTime();
}
// Adds a received message to the conversation
private void onMessageReceived(String message) {
messages.append(deviceName).append(": ").append(message).append('\n');
messagesData.postValue(messages.toString());
}
// Adds a sent message to the conversation
private void onMessageSent(String message) {
// Add it to the conversation
messages.append(getApplication().getString(R.string.you_sent)).append(": ").append(message).append('\n');
messagesData.postValue(messages.toString());
// Reset the message box
messageData.postValue("");
}
// Send a message
public void sendMessage(String message) {
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
if (deviceInterface != null && !TextUtils.isEmpty(message)) {
Log.i("info", "sendMessage: send");
}
deviceInterface.sendMessage(message);
}
public void onFinish() {
disconnect();
timer();
}
}.start();
// Check we have a connected device and the message is not empty, then send the message -----------------
}
//---------------------------------------------------------------------------MY Code
//timer
public void timer(){
new CountDownTimer(28000, 1000) {
public void onTick(long millisUntilFinished) {
Log.i("INFO", "onTick: ");
}
public void onFinish() {
connect();
}
}.start();
}
// Get Time
public void getCurrentTime() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("HHmm");
SimpleDateFormat seconds = new SimpleDateFormat("ss");
String strSec = seconds.format(calendar.getTime());
String strDate = "Time" + mdformat.format(calendar.getTime());
//if ((strSec == "29") || (strSec == "59")) {
sendMessage(strDate);
//}
}
// Called when the activity finishes - clear up after ourselves.
#Override
protected void onCleared() {
// Dispose any asynchronous operations that are running
compositeDisposable.dispose();
// Shutdown bluetooth connections
bluetoothManager.close();
}
// Helper method to create toast messages.
private void toast(#StringRes int messageResource) { Toast.makeText(getApplication(), messageResource, Toast.LENGTH_LONG).show(); }
// Getter method for the activity to use.
public LiveData<String> getMessages() { return messagesData; }
// Getter method for the activity to use.
public LiveData<ConnectionStatus> getConnectionStatus() { return connectionStatusData; }
// Getter method for the activity to use.
public LiveData<String> getDeviceName() { return deviceNameData; }
// Getter method for the activity to use.
public LiveData<String> getMessage() { return messageData; }
// An enum that is passed to the activity to indicate the current connection status
enum ConnectionStatus {
DISCONNECTED,
CONNECTING,
CONNECTED
}
}
TimeService:
package com.harrysoft.androidbluetoothserial.demoapp;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.*;
import io.reactivex.annotations.Nullable;
import static com.harrysoft.androidbluetoothserial.demoapp.App.CHANNEL_ID;
public class TimeService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
You have to pass a Context as the first argument of the Intent constructor. You can retrieved it thanks to the application object.
Intent serviceIntent = new Intent(getApplication().getApplicationContext(), TimeService.class);
I want to run my service forever in the background but it stops after sometime I checked every solution on Youtube and Internet but I didn't get the answer,I tried every solution like using START_STICKY in onStartCommand() or using onTaskRemoved() method but it did not work.Any help would be appreciated.
This is my TheService class code. `
`
package apphub.secretapp;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.os.SystemClock;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
/**
* Created by as on 12/24/2017.
*/
public class TheService extends Service implements
MediaRecorder.OnInfoListener {
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;
private MediaRecorder mRecorder;
private long mStartTime;
//setting maximum file size to be recorded
private long Audio_MAX_FILE_SIZE = 1000000;//1Mb
private int[] amplitudes = new int[100];
private int i = 0;
private File mOutputFile;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent,flags,startId);
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setOnInfoListener(this);
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setMaxFileSize(Audio_MAX_FILE_SIZE);
mRecorder.setOutputFormat
(MediaRecorder.OutputFormat.MPEG_4);
Toast.makeText(this, "Recording started", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
mRecorder.setAudioEncodingBitRate(48000);
} else {
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mRecorder.setAudioEncodingBitRate(64000);
}
mRecorder.setAudioSamplingRate(16000);
mOutputFile = getOutputFile();
mOutputFile.getParentFile().mkdirs();
mRecorder.setOutputFile(mOutputFile.getAbsolutePath());
try {
mRecorder.prepare();
mRecorder.start();
mStartTime = SystemClock.elapsedRealtime();
} catch (IOException e) {
}
}
protected void stopRecording(boolean saveFile) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
mStartTime = 0;
if (!saveFile && mOutputFile != null) {
mOutputFile.delete();
}
// to stop the service by itself
}
private File getOutputFile() {
SimpleDateFormat dateFormat = new SimpleDateFormat
("yyyyMMdd_HHmmssSSS", Locale.US);
return new File(Environment.getExternalStorageDirectory().getAbsolutePath().toString()
+ "/Voice Recorder/RECORDING_"
+ dateFormat.format(new Date())
+ ".m4a");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent i =new Intent(getApplicationContext(),this.getClass());
i.setPackage(getPackageName());
startService(i);
super.onTaskRemoved(rootIntent);
}
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) {
getOutputFile();
startRecording();
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
startRecording();
}
}
`
The simple answer is: You can't! Android is an OS created for mobile devices. Mobile devices are small battery operated computers with constrained memory. With that in mind the OS will kill your service whenever it needs memory.
In further on latest versions of the OS (specially Nougat and Oreo), those limitations are being imposed more heavily to give extra battery to users.
Any tricks, hacks and work-around you find online are just that, tricks and hacks. They might work in certain conditions or certain devices for a little bit, but you still won't have your service running forever, specially not on latest Androids.
The best scenario to try to have your Service run for as much as possible is to do two things:
return START_STICKY (like you're already doing). This indicates to the OS that you would like your Service to run for as long as possible, but there are zero guarantees that it will.
Use a foreground service. Call the methods startForeground(int, Notification) with a notification to show on the device notification panel. This will bring your process to a foreground state and allow it to stay for a bit longer, but again, no guarantees. PS.: Remember to remove the notification on your service onDestroy.
I am POST-ing the current location of my phone with the press of a button to a local webserver. The webserver receives the POSTs correctly.
However, for some reason, I can only send one location to the server, and after that the Async Task is only called once. EDIT: The Async Task is called, but the doInBackground method is not called. - then with each subsequent button press the task is not reached. I did read in the above link that it can only be called once, but I assume that's only once per object - and for some reason, this was all working just fine before I changed something and it's all screwed up.
I need to be able to send hundreds of these requests within the period of a few minutes from the phone, so any guidance here would be useful. Thanks!
package com.spencer.gps;
import android.app.Activity;
import android.content.Context;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity{
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
LocationManager mlocManager = null;
LocationListener mlocListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getAndSendLocation();
}
});
/*new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
getAndSendLocation();
}
});
}
}, 0, 1000);*/
}
public void getAndSendLocation() {
final TextView latitudeField = (TextView) findViewById(R.id.lat);
final TextView longitudeField = (TextView) findViewById(R.id.longit);
if (mlocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
latitudeField.setText("Latitude: " + MyLocationListener.latitude + '\n');
longitudeField.setText("Longitude: " + MyLocationListener.longitude + '\n');
new doPost().execute(MyLocationListener.latitude, MyLocationListener.longitude);
} else {
latitudeField.setText("GPS is not turned on...");
longitudeField.setText("GPS is not turned on...");
}
}
public class doPost extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
double lat = (Double) objects[0];
double longit = (Double) objects[1];
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.110:3000/coord");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("lat", Double.toString(lat)));
nameValuePairs.add(new BasicNameValuePair("long", Double.toString(longit)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
}
}
AsyncTask.execute()
As per doc:
Note: this function schedules the task on a queue for a single background thread or pool of threads depending on the platform version. When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting HONEYCOMB, tasks are back to being executed on a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can use the executeOnExecutor(Executor, Params...) version of this method with THREAD_POOL_EXECUTOR; however, see commentary there for warnings on its use.
So, you should call like this:
new doPost(). executeOnExecutor(AsyncTask. THREAD_POOL_EXECUTOR , MyLocationListener.latitude, MyLocationListener.longitude);
This would execute all threads in parallel, also keep an API 11 check on this method.
Hope that helps. :)
I'm trying to bind an Activity to a LocalService to interact with it. But in my Activity I am only able to make calls to methods defined in my LocalBinder and not in my LocalService. What am I doing wrong?
Not starting scratch I read another question and I have read a little how to code some sample code and my code resembles that sample code. Also I have been reading some of the Service Documentation for convenience here is a small quote from that section of the documentation:
"A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed."
But I can't do that. As mentioned above the best I can do is to have my Activity call methods defined in my LocalBinder. I have achieved nothing like the part highlighted in black above.
If it helps here are the relevant portions of my code.
LocalService to be bound to:
/**************************************************************************************************
* Filename: LocalService.java
* Project name: Local Service Sample
* Application name: Local Service
* Description: This file contains the LocalService (extends Service) for our Local Service app
**************************************************************************************************/
package com.marie.localservicesample;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;
public class LocalService extends Service {
private NotificationManager mNM;
// Unique Identification Number for the Notification.
// We use it on Notification start, and to cancel it.
private int NOTIFICATION = R.string.local_service_started;
// just some arbitrary numbers for test purposes
public static int statusCode = 99;
public static int emptyMsg = 549;
// I get my Extras from onStartCommand and use in ServiceWorker() thread
public static final String EXTRA_MAC = "com.marie.localservicesample.EXTRA_MAC";
private String macString;
public static final String EXTRA_MESSENGER = "com.marie.localservicesample.EXTRA_MESSENGER";
private Messenger messenger;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//private static final String macString = "00:06:66:02:D0:EC";
Boolean stop_receive_data = false;
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example - or not because
// this is a local service
private final IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
Log.i("onBind", "called in LocalService" );
Log.i("onBind", "intent: " + intent.toString());
Log.i("onBind", "mBinder: " + mBinder);
return mBinder;
}
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
showNotification();
}
// Call this at the end of onStartCommand() after we got the Extras
public void afterStartCommand() {
Thread thr = new Thread(null, new ServiceWorker(), "LocalService");
thr.start();
}
/*
* This is the ServiceWorker thread that passes messages to the handler defined in
* the Controller activity.
*/
class ServiceWorker implements Runnable
{
public void run() {
// do background processing here... something simple
Looper.prepare();
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice btDevice = btAdapter.getRemoteDevice(macString);
BluetoothSocket btSocket = null;
InputStream btIstream = null;
OutputStream btOstream = null;
try {
btSocket = btDevice.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
btSocket.connect();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
btIstream = btSocket.getInputStream();
btOstream = btSocket.getOutputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
int data = btIstream.read();
// reset the bluetooth device
while (data != 63) {
Log.d("LocalService", "resetting bluetooth device");
btOstream.write('r');
data = btIstream.read();
}
StringBuffer strBuffer = new StringBuffer("");
Boolean dataBegin = false;
int ndxPlus = 0;
while (data != -1) {
char printableB = (char) data;
if (data < 32 || data > 126) {
//printableB = ' ';
}
//Log.d("LocalService", Character.toString(printableB) + "(" + data + ")");
if (data == 63) {
btOstream.write('$');
btOstream.write(',');
}
if (data == 45) {
btOstream.write('1');
btOstream.write(',');
dataBegin = true;
}
if (dataBegin == true) {
strBuffer = strBuffer.append(Character.toString(printableB));
}
if (data == 13) {
dataBegin = false;
//Log.d("LocalServiceDataString", strBuffer.toString());
// send data to the handler to plot the data
Message msg = Message.obtain();
msg.what = Controller.MESSAGE_MAC;
msg.obj = strBuffer;
try {
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
strBuffer = new StringBuffer("");
if (ndxPlus < 0) {
btOstream.write('+');
ndxPlus++;
}
}
data = btIstream.read();
if (stop_receive_data) data = -1;
}
} catch (IOException e1) {
e1.printStackTrace();
}
try {
btSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
LocalService.this.stopSelf();
Looper.loop();
// stop the service when done...
// Or use the unbindBtn in the MainActivity class?
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
Bundle extras = intent.getExtras();
messenger = (Messenger)extras.get(EXTRA_MESSENGER);
macString = extras.getString(EXTRA_MAC);
afterStartCommand();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancel(NOTIFICATION);
stop_receive_data = true;
// Tell the user we stopped.
Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
}
/**
* Show a notification while this service is running.
*/
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.local_service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text, System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Controller.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.local_service_label), text, contentIntent);
// Send the notification.
mNM.notify(NOTIFICATION, notification);
}
}
Activity that binds to LocalService:
/**************************************************************************************************
* Filename: Binding.java
* Project name: Local Service Sample
* Application name: Local Service
* Description: This file contains the Binding class for our Local Service application
**************************************************************************************************/
package com.marie.localservicesample;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/*
* Example of binding and unbinding to the local service.
* This demonstrates the implementation of a service which the client will
* bind to, receiving an object through which it can communicate with the service.
*/
public class Binding extends Activity {
private ILocalBinder mBoundService;
private boolean mIsBound;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
mBoundService = (ILocalBinder)service;
int statusCode = mBoundService.getStatusCode();
Log.d("Binding.java","called onServiceConnected. statusCode: " + statusCode);
Toast.makeText(Binding.this, R.string.local_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
mBoundService = null;
Log.d("Binding", "called onServiceDisconnected");
Toast.makeText(Binding.this, R.string.local_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(Binding.this, LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
int statusCode = mBoundService.getStatusCode();
if (statusCode != 0) Log.d("doUnbindService", "Binding.java statusCode: " + statusCode);
// Tell the user we did an unbind
Toast.makeText(this, R.string.local_service_unbound, Toast.LENGTH_SHORT).show();
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.local_service_binding);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.bind);
button.setOnClickListener(mBindListener);
button = (Button)findViewById(R.id.unbind);
button.setOnClickListener(mUnbindListener);
}
private OnClickListener mBindListener = new OnClickListener() {
public void onClick(View v) {
doBindService();
}
};
private OnClickListener mUnbindListener = new OnClickListener() {
public void onClick(View v) {
doUnbindService();
}
};
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
}
My ILocalBinder and LocalBinder:
/**************************************************************************************************
* Filename: ILocalBinder.java
* Project name: Local Service Sample
* Application name: Local Service
* Description: This file contains an example interface for my LocalBinder
**************************************************************************************************/
package com.marie.localservicesample;
public interface ILocalBinder {
public int getStatusCode();
}
/**************************************************************************************************
* Filename: LocalBinder.java
* Project name: Local Service Sample
* Application name: Local Service
* Description: This file contains the LocalBinder class for our Local Service application
**************************************************************************************************/
package com.marie.localservicesample;
import android.os.Binder;
import com.marie.localservicesample.LocalService;
/**
* Class for clients to access. Because we know this service always
* runs in the same process as its clients, we don't need to deal with
* IPC.
*/
public class LocalBinder extends Binder implements ILocalBinder {
#Override
public int getStatusCode() {
return LocalService.statusCode;
}
}
Thanks!
See the local service example.
Just copy the binder class code they have into your service instead of making a separate file for it: (inside the LocalService class declaration)
public class LocalService {
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
/**
* Class for clients to access. Because we know this service always
* runs in the same process as its clients, we don't need to deal with
* IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
...
}
and then:
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
mBoundService = ((LocalService.LocalBinder)service).getService();
Now you can access your service directly using mBoundService.
i am working on a task scheduler applications as my college project, i have a service that checks the expire time of an task. i had implemented handlers to check the expire time. When the expire time of an application is matched with current time then it sends a status bar notification. At this point i am pausing the Thread using Thread.sleep method for a minute, which is causing my application to hang. At logcat it shows heavy CPU usages by applications.
i am fetching the data from database, but it works fine when Thread.sleep is not called.
Please help.
Here is the code:
package com.apps.niit.taskm;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class ExpireTimeService extends Service {
DataHelper dh;
ArrayList<String> tData=new ArrayList<String>();
String date;
Calendar c;
String str;
String str1;
String str2;
String str3;
String str4;
String str5;
int notificationID=1;
String [][] data;
NotificationManager notificationManager;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate(){
super.onCreate();
dh = new DataHelper(this);
fetchData();
handler.removeCallbacks(updateTimeTask);
handler.postDelayed(updateTimeTask, 1000);
}
public void fetchData(){
String eDate = android.text.format.DateFormat.format("d/M/yyyy", new java.util.Date()).toString();
tData.addAll(this.dh.selectDate(eDate));
data =new String[tData.size()][4];
if(!tData.isEmpty()){
for(int i=0; i<tData.size();i++){
breakString(tData.get(i));
data[i][0]=str1;
data[i][1]=str2;
data[i][2]=str3;
data[i][3]=str4;
}
}
}
public void stopService(){
stopSelf();
}
private Runnable updateTimeTask = new Runnable() {
public void run(){
try {
String time = android.text.format.DateFormat.format("k:m", new java.util.Date()).toString();
for(int i=0; i<tData.size();i++){
if(data[i][3].equals(time)){
//send notification code goes here
String serName = Context.NOTIFICATION_SERVICE;
notificationManager = (NotificationManager)getSystemService(serName);
String ticker= data[i][0]+" "+data[i][1]+" "+data[i][2]+" "+data[i][3];
long when= System.currentTimeMillis();
int icon = R.drawable.icon;
Notification notification = new Notification(icon, ticker,when);
Intent intent = new Intent (getApplicationContext(), DisplayTask.class);
Bundle myBundle = new Bundle();
myBundle.putString("str1", data[i][0]);
myBundle.putString("str2", data[i][1]);Log.i("data1",data[i][1]);
myBundle.putString("str3", data[i][2]);Log.i("data1",data[i][2]);
myBundle.putString("str4", data[i][3]);Log.i("data1",data[i][3]);
intent.putExtras(myBundle);
PendingIntent launchIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
notification.setLatestEventInfo(getApplicationContext(), "", "", launchIntent);
notificationID=1;
notificationManager.notify(notificationID, notification);
Thread.sleep(10000);
}
}
handler.postDelayed(this, 1000);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("Error from service", e.toString());
}
}
};
private void breakString(String str) {
// TODO Auto-generated method stub
str1 = str.substring(0, str.indexOf(";"));
str = str.substring(str1.length()+1, str.length());
str2 = str.substring(0, str.indexOf(";"));
str = str.substring(str2.length()+1, str.length());
str3 = str.substring(0, str.indexOf(";"));
str4 = str.substring(str3.length()+1, str.length());
}
#Override
public void onDestroy() {
super.onDestroy();
if (handler != null)
handler.removeCallbacks(updateTimeTask);
handler = null;
}
private Handler handler = new Handler();
}
When you're using Handler's postDelayed function here is what happens:
Handler puts your Runnable into the current thread's Looper queue.
When time comes, your code in Runnable is run on the UI thread.
Note that its not that Handler always puts Runnable to UI thread queue. It puts Runnable to current thread's queue, and your current thread was the UI thread.
So if you put Thread.sleep or anything time consuming (like network communication) in that updateTimeTask it will hang the whole UI thread.
In your case you should use ScheduledExecutorService, see scheduleWithFixedDelay function. Or as alternative, you can start AsyncTask from your updateTimeTask function and do all heavy-lifting and Thread.sleep in doInBackgrund function.