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();
}
}
Related
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
I have got an infinite IntentService meant to enable scanner for all the time application is alive. And whenever there is a breakpoint - it works fine. But when I remove a breakpoint from a loop - it stops working after some time. And then again when I put a breakpoint - it starts working again. What the heck? How can I fix this?
protected void onHandleIntent(#Nullable Intent intent)
{
final Handler handler = new Handler();
handler.post(new Runnable()
{
#Override
public void run()
{
while(true)
{
if (!blocked)
{
blocked = true;
String received = GlobalAccess.scan.scan(1000);
if (received != null && !received.isEmpty())
{
//TODO: some stuff here
}
blocked = false;
}
else
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
});
}
EDIT
I have created my CustomService with
#Override
public void onCreate()
{
super.onCreate();
scheduledExecutorService = Executors.newScheduledThreadPool(1);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
final Handler handler = new Handler();
Runnable runnable = new Runnable()
{
#Override
public void run()
{
while(true)
{
if (!blocked)
{
blocked = true;
String received = GlobalAccess.scan.scan(1000);
if (!Objects.equals(received, null) && !received.isEmpty())
{
//TODO: some stuff here
}
blocked = false;
}
else
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
};
ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(runnable, 0, TimeUnit.MILLISECONDS);
return START_STICKY;
}
But it has exact same bahavior as IntentService
Thanks to #CommonsWare I have managed to solve my problem.
This is the solution:
public class ScanService extends Service
{
ScheduledExecutorService scheduledExecutorService;
#Override
public void onCreate()
{
super.onCreate();
scheduledExecutorService = Executors.newScheduledThreadPool(1);
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
String received = GlobalAccess.scan.scan(1000);
if (!Objects.equals(received, null) && !received.isEmpty())
{
//TODO: some stuff here
}
}
};
scheduledExecutorService.scheduleWithFixedDelay(runnable, 0, 50, TimeUnit.MILLISECONDS);
return START_STICKY;
}
}
I have searched and found questions similar to the title, but no solution so far.
I have the following service
public class MyService extends Service {
public MyService() {
}
private static final String TAG =
"ServiceExample";
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service onCreate");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service onStartCommand " + startId);
final int currentId = startId;
Runnable r = new Runnable() {
public void run() {
for (int i = 0; i < 3; i++)
{
long endTime = System.currentTimeMillis() +
10*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime -
System.currentTimeMillis());
} catch (Exception e) {
}
}
}
Log.i(TAG, "Service running " + currentId);
}
//stopSelf();
}
};
Thread t = new Thread(r);
t.start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
Log.i(TAG, "Service onDestroy");
super.onDestroy();
//Log.i(TAG, "Service Destroyed");
}
}
And this is called from my activity that has two buttons: One for starting the service and one for stopping it
public class ServiceExampleActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_example);
}
public void buttonClick(View view)
{
Intent intent = new Intent(this, MyService.class);
startService(intent);
}
public void stopClick(View view)
{
Intent intent = new Intent(this, MyService.class);
stopService(intent);
}
}
However this does not work. The service is not stopped.
Strangely the onDestroy function is called but after that the runnable is still running.
How can I stop the service?
=============================================
EDIT: I finally achieved it by the following changes:
In the onDestroy function
#Override
public void onDestroy() {
Log.i(TAG, "Service onDestroy");
// mHandler.removeCallbacks(r);
t.interrupt();
super.onDestroy();
//Log.i(TAG, "Service Destroyed");
}
the thread t had to be a class member (before it was declared inside onStartCommand) and I modified the runnable as this
r = new Runnable() {
public void run() {
for (int i = 0; i < 3; i++)
{
long endTime = System.currentTimeMillis() +
10*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime -
System.currentTimeMillis());
} catch (Exception e) {
return; //HERE to detect if the thread has been interrupted
}
}
}
Log.i(TAG, "Service running " + currentId);
}
stopSelf();//I have to use this otherwise it doesn't stop
}
};
I wonder why normally I have to use stopSelf but when interrupted it is not necessary. I suppose stopSelf just calls onDestroy
Stopping a service just kills the context. The framework does not know about any other Threads you may have started- its your job to kill them in onDestroy(). Save the Thread when you create it. In onDestroy(), interrupt it. And in your thread's runnable, regularly check to see if the Thread is interrupted, and return if so. Do not call Thread.stop(), as it may leave your app in an unsafe state.
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;
}
}
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.