I'm using an implementation of android.media.projection.MediaProjection to get images and it is working just fine. However when calling myService.myRunnable.run() from MainActivity, the callback onImageAvailable() stop getting called. Where myService is a Foreground Service bound to the activity, and myRunnable a Runnable object member of myService.
public class MainActivity extends Activity {
private MyService myService;
ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
isServiceBounded = false;
myService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
isServiceBounded = true;
MyService.LocalBinder mLocalBinder = (MyService.LocalBinder) service;
myService = mLocalBinder.getServerInstance();
}
};
public class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
#Override
public void onImageAvailable(ImageReader reader) {
Log.d(TAG, "this is called for each new frame until the button is pressed");
...
}
#Override
protected void onCreate(Bundle savedInstanceState) {
button.setOnClickListener(views -> {
myService.myRunnable.run()
});
if (!isMyServiceRunning(MyService.class)) {
startMyService();
bindToMyService();
}
}
#Override
protected void onDestroy() {
myService.killMyRunnable();// -> myRunnable = null;
stopMyService();
unbindService(mConnection);
super.onDestroy();
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
...
if (running) ? return true : return false;
}
}
,
public class MyService extends Service {
IBinder mBinder = new LocalBinder();
public MyRunnable myRunnable;
public class LocalBinder extends Binder {
public MyService getServerInstance() {
return MyService.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
}
...
}
,
public class MyRunnable implements Runnable {
private void dummyWorkload(){
Log.d(TAG, "dummyWorkload: isWorking");
try {
Thread.sleep(2000);
dummyWorkload();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void run() {
dummyWorkload();
}
}
What is causing this issue?
The code stops the MediaProjection because it invokes myRunnable.run() from the MainThread, therefore freezing the UI while the runnable is busy. For the projection to continue working it should be called from a separate Thread. To solve the issue, either extends Thread instead of implements Runnable interface or call the Runnable this way:
Thread myThread = new Thread(new myRunnable);
myThread.start();
Related
I am trying to create a service class with a inner class which is a Handler class , unfortunately I am not able to access handler.obtainMessage() in this class .. Can any one give suggestions on this ?
Source code for the Service class:
public class MyService extends Service {
private MyHandler myHandler;
private final class MyHandler extends Handler {
public MyHandler(Looper looper) {
super(looper);
}
public void handleMessage(Message msg) {
try {
Thread.sleep(5000);
// use the unique startId so you don't stop the
// service while processing other requests
stopSelfResult(msg.arg1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void close() {
}
#Override
public void flush() {
}
#Override
public void publish(LogRecord record) {
}
}
#Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();
// Create a new HandlerThread with a specified priority
HandlerThread thread = new HandlerThread("MyHandlerThread",Thread.NORM_PRIORITY);
// Start the handler thread so that our Handler queue will start
// processing messages
thread.start();
// Run the handler using the new HandlerThread
myHandler = new MyHandler(thread.getLooper());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Message msg = myHandler.obtainMessage();
msg.arg1 = startId;
myHandler.sendMessage(msg);
return START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Done", Toast.LENGTH_SHORT).show();
}
}
You've got the wrong Handler class imported. It should be android.os.Handler, not java.util.logging.Handler.
I want to instantiate a thread in a Service that will work even when the client leaves the app. On his return the Tread will not be instantiated again only certain parameters of it may be changed. So I need to be able to access it. It also concerns rotation of the screen.
The current code starts another thread which is obviously not a desired solution. The commented out stuff shows different approaches but they didn't work either. I will have to access threadService object in main activity as well.
public class MainActivity extends ActionBarActivity {
private static ThreadService threadService;
private ServiceConnection threadConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
ThreadServiceBinder binder = (ThreadServiceBinder) service;
threadService = binder.getService();
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, ThreadService.class);
this.startService(intent);
/* if(threadConnection == null) {
Intent intent = new Intent(this, ThreadService.class);
this.startService(intent);
Toast.makeText(this, "Thread service is null", Toast.LENGTH_SHORT).show();
} else {
if(!threadService.ifThreadIsRunning()) {
Intent intent = new Intent(this, ThreadService.class);
this.startService(intent);
Toast.makeText(this, "Thread service is not null", Toast.LENGTH_SHORT).show();
}
}*/
}
#Override
public void onDestroy() {
this.stopService(new Intent(this, ThreadService.class));
super.onDestroy();
}
/*
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}*/
}
Here is the service
public class ThreadService extends Service {
private final IBinder threadServiceBinder = new ThreadServiceBinder();
public class ThreadServiceBinder extends Binder {
ThreadService getService() {
return ThreadService.this;
}
}
final Handler handler = new Handler();
private BackgroundThread backgroundThread;
public ThreadService() {
/*
* if(backgroundThread == null) backgroundThread =new
* BackgroundThread(handler);
*/
backgroundThread = BackgroundThread.getInstance();
backgroundThread.setHandler(handler);
handler.removeCallbacks(backgroundThread);
handler.postDelayed(backgroundThread, 10000);
}
#Override
public IBinder onBind(Intent intent) {
return threadServiceBinder;
}
public boolean ifThreadIsRunning() {
if (backgroundThread.isAlive()) {
return true;
} else {
return false;
}
}
}
class BackgroundThread extends Thread {
private static BackgroundThread instance;
private Handler mHandler;
private BackgroundThread() {
}
public static synchronized BackgroundThread getInstance() {
if (instance == null) {
instance = new BackgroundThread();
}
return instance;
}
public void setHandler(Handler handler) {
if (mHandler == null) {
mHandler = handler;
}
}
/*
* public BackgroundThread(Handler handler) { super(); mHandler = handler; }
*/
#Override
public void run() {
try {
Log.d("com.example.timer", "We are in Runnable run try section");
mHandler.postDelayed(this, 10000);
} catch (Exception e) {
// TODO: handle exception
}
/*
* finally{ handler.postDelayed(runable, 2000); }
*/
}
}
I have a simple Service
public class UpdateService extends Service {
private int seconds;
final static String MY_ACTION = "MY_ACTION";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
timer.start();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
final CountDownTimer timer = new CountDownTimer(86400000, 1000) {
public void onTick(long millisUntilFinished) {
Util.saveInfo(getApplicationContext(), Util.SECONDS, seconds++);
Intent intent = new Intent();
intent.setAction(MY_ACTION);
sendBroadcast(intent);
}
public void onFinish() { }
};
}
When I close an application service stops working. But showing that the service is running.
What am I doing wrong?
Update
I changed CountDownTimer to Thread, but the problem remained
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
Util.saveInfo(getApplicationContext(), Util.SECONDS, seconds++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
OnStart()
if(!t1.isAlive())
t1.start();
Because CountDown Timer is working only foreground means app is running and not minimized or closed. You have to place a Thread in Service that executing at particular time of you want.
try this :
public class LocalService extends Service
{
private static Timer timer = new Timer();
private Context ctx;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
ctx = this;
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
}
private class mainTask extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
private final Handler toastHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
System.out.println("test");
}
};
}
I have a checked button in my MainActivity. If that button is checked it should start the service but if a user unchecked the button I want to stop the service.
So in uncheck condition I have written this stopService(intentname); but the problem is the service is not stopping. Here is my code snippet:
Service Class
public class SimpleService extends Service
{
String selectedAudioPath = "";
private MyThread myythread;
public Intent intent;
public boolean isRunning = false;
long interval=30000;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
myythread = new MyThread(interval);
}
#Override
public synchronized void onDestroy()
{
super.onDestroy();
if(!isRunning)
{
myythread.interrupt();
myythread.stop();
isRunning = false;
}
}
#Override
public synchronized void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
if(!isRunning)
{
//this.intent = intent;
//System.out.println("the intent is" + intent);
myythread.start();
isRunning = true;
}
}
class MyThread extends Thread
{
long interval;
public MyThread(long interval)
{
this.interval=interval;
}
#Override
public void run()
{
while(isRunning)
{
System.out.println("Service running");
try
{
String myString = intent.getStringExtra("name");
if(myString == null)
Log.d("Service","null");
else
{
Log.d("Service","not null");
if(myString.equalsIgnoreCase("image"))
{
uploadImages();
Thread.sleep(interval);
}
else if(myString.equalsIgnoreCase("audio"))
{
uploadAudio();
Thread.sleep(interval);
}
}
}
catch (InterruptedException e)
{
isRunning = false;
e.printStackTrace();
}
}
}
You can't stop a thread that has a running unstoppable loop like this
while(true)
{
}
To stop that thread, declare a boolean variable and use it in while-loop condition.
public class MyService extends Service {
...
private Thread mythread;
private boolean running;
#Override
public void onDestroy()
{
running = false;
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startid) {
running = true;
mythread = new Thread() {
#Override
public void run() {
while(running) {
MY CODE TO RUN;
}
}
};
};
mythread.start();
}
Source: Stopping a thread inside a service
Don't use Threads. Use AsyncTask instead.
public class MyService extends Service {
private AsyncTask<Void,Void,Void> myTask;
#Override
public void onDestroy(){
super.onDestroy();
myTask.cancel(true);
}
#Override
public void onStart(Intent intent, int startid) {
myTask = new AsyncTask<Void,Void,Void>(){
#Override
public void doInBackground(Void aVoid[]){
doYourWorkHere();
}
}
myTask.execute();
}
}
I am having problems running a timer in a service I have created. The task that the timer calls simply isn't called. I know that the service starts as I have put toasts within it and they are called, but not when they are within the timer. Help appreciated.
service class:
public class LocalService extends Service
{
private static Timer timer = new Timer();
private Context ctx;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
ctx = this;
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
}
private class mainTask extends TimerTask
{
public void run()
{
Toast.makeText(ctx, "test", Toast.LENGTH_SHORT).show();
}
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
}
Main class:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(RingerSchedule.this, LocalService.class));
}
Android does not allow UI events like Toasts from outside the main thread. The run is getting called, but the Toast is being ignored.
To create the Toast on the UI thread, you can use a Handler and an empty Message like so:
public class LocalService extends Service
{
private static Timer timer = new Timer();
private Context ctx;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
super.onCreate();
ctx = this;
startService();
}
private void startService()
{
timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
}
private class mainTask extends TimerTask
{
public void run()
{
toastHandler.sendEmptyMessage(0);
}
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
private final Handler toastHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
}
};
}
Thanks, I also needed to cancel the timer ..
public void onDestroy() {
timer.cancel();
Toast.makeText(this, "ServiceTalkGeology stopped.",
Toast.LENGTH_SHORT).show();
super.onDestroy();
}