I am trying to load an URL (API) after every 15 seconds in a service. Everything is working fine but when the app is killed URL is not called. I dont need any UI in my app. I just want it to work in background when the app is killed. I have been finding a solution for two days but nothing worked. Please help!
Here is my service code :
public class MyService extends Service {
Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000;
String data ;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
handler.postDelayed( runnable = new Runnable() {
public void run() {
data = (String) intent.getExtras().get("data");
Toast.makeText(MyService.this, ""+data, Toast.LENGTH_SHORT).show();
loadURL(data);
handler.postDelayed(runnable, delay);
}
}, delay);
return START_STICKY ;
}
#Override
public void onDestroy() {
handler.postDelayed( runnable = new Runnable() {
public void run() {
Toast.makeText(MyService.this, ""+data, Toast.LENGTH_SHORT).show();
loadURL(data);
handler.postDelayed(runnable, delay);
}
}, delay);
}
public void loadURL(String data){
try{
RequestFuture<JSONObject> requestFuture=RequestFuture.newFuture();
final String mURL = "http://192.168.1.12/att.php?emp_id=" + data + "&status=&submit=Insert";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
mURL,new JSONObject(),requestFuture,requestFuture);
MySingleton.getInstance(this).addToRequestQueue(request);
Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
try {
JSONObject object= requestFuture.get(10, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e){
Toast.makeText(this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
Here is my MainActivity.java where I am getting an intent as a userID :
public class MainActivity extends AppCompatActivity {
String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = getIntent().getStringExtra("ID");
Intent intent = new Intent(MainActivity.this, MyService.class);
intent.putExtra("data", data);
startService(intent);
}
}
You will have to turn that background service into a foreground service, because of the limitations called Background Execution Limits that started from android Oreo.
Please check out this link for more better understanding:
https://developer.android.com/about/versions/oreo/background
Related
i have a problem in my service, the service is runnig from MainActivity (i am doing test) and extends of service.
i want to use the service from foreground and background (when the app is closed) and i already have my first problem:
my service(have a counter that is displayed by LOG) is restarting when i close the app.
also i want to be able to use the service with the open app and close app, in other words to use both the Service Started and Link Service
public class MyService extends Service {
private Thread backgroundThread;
private boolean isRunning;
public MyService() {
Log.e("MyService","constructor");
}
#Override
public void onCreate() {
super.onCreate();
isRunning = false;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Log.e("onStartCommand","Servicio Llamado");
if (!this.isRunning) {
Log.e("onStartCommand","hilo iniciandose");
this.backgroundThread = new Thread(myTask);
runTask();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("onDestroy","servicio destuido");
}
private void runTask(){
this.isRunning = true;
this.backgroundThread.start();
}
private Runnable myTask = new Runnable() {
public void run() {
Log.e("myTask","hilo iniciado");
int i = 0;
do{
pauseService();
Log.e("myTask","hilo contador: "+i);
//Toast.makeText(getApplicationContext(),"CONTADOR = "+j, Toast.LENGTH_SHORT).show(); //no working :(
i++;
}while (i<10);
/*
//linea de detencion del servicio
//stopSelf();
isRunning=false;
backgroundThread.interrupt();
//backgroundThread = new Thread(myTask);
*/
Log.e("myTask","hilo cerrado");
}
};
private void pauseService(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In main Activity
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("iteraciones",10);
startService(intent);
why because the service restarts when I close the application and how can I avoid it?
Service stop working when turn on /of Wi-Fi many time, when I start service do counter 1,2,3 etc or any thing then turn on /of Wi-Fi many time the service stops working ,I have BroadcastReceiver class doing start service, no exceptions , error appear , only I sent one message to phone to start service..
This is the code inside BroadcastReceiver:
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Intent recorderIntent = new Intent(context, Start2.class);
context.startService(recorderIntent);
}
This My Start2 Service:
public class Start2 extends Service {
private static final String TAG = Start2.class.getSimpleName();
int mStartMode;
#Override
public void onDestroy() {
Log.d(TAG, "Stop Service onDestroy");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
final Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
int i = 0 ;
#Override
public void run() {
try{
//do your code here
Log.d(TAG, "Start Service Repeat Time.. " + i);
i++;
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed( this, 5000 );
}
}
};
handler.postDelayed(runnable, 1000 );
return null;
}
};
task.execute();
return mStartMode;
}
}
I want to operate two threads in the service.
I want to operate pThread only once in the onCreate
and
I want to continue to operate t-Thread in the onStartCommand.
If two threads operate independently, it works correctly.
but When operating as shown in the following source, it works incorrectly.
Perhaps, t-thread seems to operate before pThread is complete.
I want to t-Thread is operating after pThread is complete.
The source code is below.
public class BeaconService extends Service {
CentralManager centralManager;
private final String SERVER_ADDRESS = "http://xxx.xxx.xxx.xxx";
Handler handler;
XmlParser xmlGetter = new XmlParser();
Thread t;
Thread pThread;
String result = "d5756247-57a2-4344-915d-9599497940a7";
String text;
int count=0;
HashMap<String, Long> key = new HashMap<String, Long>();
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate(){
super.onCreate();
setCentralManager();
handler = new Handler(Looper.getMainLooper());
t = new Thread(new Runnable() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
centralManager.startScanning();
}
});
}
});
pThread = new Thread(new Runnable() {
#Override
public void run() {
try{
URL url = new URL(SERVER_ADDRESS + "/Beacon_Infor.php?");
Log.i("url","url : "+url);
url.openStream();
Log.i("stream","success");
}catch(Exception e){
Log.e("Error", "Error : " + e.getMessage());
}
}
});
pThread.start();
Log.i("Service", "Start");
Toast.makeText(this, "Service Start", Toast.LENGTH_SHORT).show();
key=xmlGetter.getXmlHash("result.xml");
Log.i("beacon hash", "hash : " + key);
}
public int onStartCommand(Intent intent, int flags, int startId){
Log.i("onStartCommand", "Start");
t.start();
return START_STICKY;
}
public void onDestroy(){
Toast.makeText(this, "Service End", Toast.LENGTH_SHORT).show();
if(centralManager.isScanning()) {
centralManager.stopScanning();
}
centralManager.close();
super.onDestroy();
}
}
I know there are a lot of questions on this already but it doesn't seem to work, so basically I have a custom Service, the service works fine when the timer inside it expires, and calls the stopservice method. however when I try and stop the service from another activity it doesn't work?
code for custom service:
public class ConnectionService extends Service {
Intent service_intent;
Timer t;
int expiry_time = 0;
int timer_tick_starter = 0;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
t = new Timer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
service_intent = intent;
Log.d("onConnectionService", "onStartCommand");
expiry_time = Integer.parseInt(intent.getStringExtra("expiry"));
//convert the minutes to milliseconds
timer_tick_starter = (expiry_time * 60000);
Log.d("onConnectionService", "Expiry Time (in milliseconds) " + timer_tick_starter);
} catch (Exception e) {
Log.d("onConnectionService", e.getMessage().toString());
}
//timer will only start to run on the expiry_time which will then close the connection
t.schedule(new TimerTask() {
#Override
public void run() {
Log.d("onConnectionService", "inside expiry time");
//close the connection
stopService(service_intent);
}
}, 30000);
return START_NOT_STICKY;
}
#Override
public boolean stopService(Intent name) {
Log.d("onConnectionService", "StopService called");
String message = name.getStringExtra("msg");
//broadcast sender
Intent intent = new Intent();
intent.putExtra("msg", message);
intent.setAction("fi.android.inetkeyapplication.CUSTOM_INTENT");
intent.putExtra("is_selected", UserConnectionState.getInstance().is_selected);
sendBroadcast(intent);
Log.d("onConnectionService", "Service has been killed");
return super.stopService(name);
}
#Override
public void onDestroy() {
Log.d("onConnectionService", "Destroy called");
}
}
here I start the service from onCreate:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Log.d("onConfigurationActivity", "Service starting ");
// Intent i = new Intent(ConfigurationActivity.this, ConnectionService.class);
Intent i = new Intent(context, ConnectionService.class);
i.putExtra("expiry", "1");
startService(i);
}
});
thread.start();
however later in my app when I try to kill it from the activity in which I start it, it doesn't work:
Button exit_button = (Button) findViewById(R.id.btnExit);
connect_button.setTypeface(roboto_light);
exit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do closing call
response_close = "";
//need to close service
//also kill the service
Log.d("onConfigurationActivity", "killing service");
Intent intent = new Intent(context, ConnectionService.class);
intent.putExtra("msg", "You have been disconnected");
stopService(intent);
}
});
I have tried my class - ConfigurationActivity.this (as context) and I have tried (this) at the moment I am using a custom context that I simply get inside onCreate. however nothing seems to work what am I missing?
thanx
ok so apparently stopping the service doesn't stop the timer. so I just called cancel() on timer
First I will explain the current situation.
I've 2 different threads in 2 services(read from usb port service and make web requests service). I'm starting them in onCreate of my activity like:
serialServiceIntent = new Intent(NDKSerialActivity.this, SerialService.class);
startService(serialServiceIntent);
webServiceIntent = new Intent(NDKSerialActivity.this, RecordWebService.class);
startService(webServiceIntent);
There is nothing wrong with serial service but in RecordWebService when I make a request my gui stops until response comes.
The code is like that:
public class RecordWebService extends Service
{
public static final String SERVER_ADDRESS = "http://192.168.1.100:8080/MobilHM/rest";
private static final String TAG = RecordWebService.class.getSimpleName();
private RecordWebThread recordWebThread;
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
recordWebThread = new RecordWebThread(true);
recordWebThread.start();
}
#Override
public void onDestroy()
{
super.onDestroy();
Log.i(TAG, "RecordWebService Destroyed");
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
and
public class RecordWebThread extends Thread
{
private static final String TAG = RecordWebThread.class.getSimpleName();
public boolean always;
public RecordWebThread(boolean always)
{
this.always = always;
}
#Override
public void run()
{
PatientRecord patientRecord = new PatientRecord();
while (always)
{
RestClient restClient = new RestClient(RecordWebService.SERVER_ADDRESS + "/hello");
try
{
restClient.execute(RequestMethod.GET);
}
catch (Exception e1)
{
Log.e(TAG, "", e1);
}
Log.i(TAG, "Server Response Code:->" + restClient.getResponseCode());
Log.i(TAG, "Server Response:->" + restClient.getResponse());
try
{
sleep(4 * 1000);
}
catch (InterruptedException e)
{
Log.e(TAG, "Web service interrupted", e);
}
}
}
}
Also I've tried to remove sleep part and make the thread to run with timer and timer task like:
public void sendRecord()
{
scanTask = new TimerTask()
{
public void run()
{
handler.post(new Runnable()
{
public void run()
{
RestClient restClient = new RestClient(RecordWebService.SERVER_ADDRESS + "/hello");
try
{
restClient.execute(RequestMethod.GET);
}
catch (Exception e1)
{
Log.e(TAG, "", e1);
}
Log.i(TAG, "Server Response Code:->" + restClient.getResponseCode());
Log.i(TAG, "Server Response:->" + restClient.getResponse());
}
});
}
};
t.schedule(scanTask, 1000, 4000);
}
but no luck, my gui hangs when it comes to restClient.execute .
You can find RestClient.java # http://www.giantflyingsaucer.com/blog/?p=1462
How can I make my requests not block my gui thread?
Edit:
public void sendRecord()
{
scanTask = new TimerTask()
{
public void run()
{
RestClient restClient = new RestClient(RecordWebService.SERVER_ADDRESS + "/hello");
try
{
restClient.execute(RequestMethod.GET);
}
catch (Exception e1)
{
Log.e(TAG, "", e1);
}
Log.i(TAG, "Server Response Code:->" + restClient.getResponseCode());
Log.i(TAG, "Server Response:->" + restClient.getResponse());
}
};
t.schedule(scanTask, 1000, 4000);
}
Without handler, I call this in onCreate of my activity but still ui hanging.
Or you can use an IntentService which will handle the thread issues for you.
This is an example class:
public class MyService extends IntentService {
public MyService() {
super("MyService");
}
public MyService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent arg0) {
//Do what you want
}
}
Then you just call:
Intent intent = new Intent(getApplicationContext(),MyService.class);
startService(intent);
Edit:
To repeat the same thing every 4 seconds you should do something like this:
PendingIntent serviceIntent= PendingIntent.getService(context,
0, new Intent(context, MyService.class), 0);
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
long intervalInSec = 4;
am.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, intervalInSec*1000, serviceIntent)
;
In your code (2d version) happens next: You create thread, and it asks UI thread to do some net interaction. Just exclude handler.post(...) while executing request. Later you can use this for simple runnable for updating your UI with results of request.