My TTS in service is not stopping and speak two times.
In logcat the error is "stop failed: not bound to TTS engine"
I am stuck here that why TTS is not stoping. What wil I do here to stop it when speaked.
Here is my code
public class Speaker extends Service implements TextToSpeech.OnInitListener {
public static TextToSpeech mtts;
String speech = "";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
}
#Override
public void onStart(Intent intent, int startid) {
speech=intent.getExtras().getString("speech");
mtts = new TextToSpeech(getApplicationContext(), this);
}
#Override
public void onDestroy() {
if (mtts != null) {
Log.e("Destroy", "Service");
mtts.stop();
mtts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS)
mtts.speak(speech, TextToSpeech.QUEUE_ADD, null);
}
Log.e("onInit ends", "Service");
}
}
}
One reason is that when a phone call is incoming then at this time your broadcast receiver would be calling this activity again and again unless you pick the phone
If you want to stop this service after make it speak for once.
Code for stopping the service.
Intent in = new Intent(this, Speaker.class);
stopService(in);
Use this code inside onDestroy() or in onStart() method.
Why you are using the service for TTS?, you can use any activity or class etc.
Related
I have created a service and called this service class from BaseActivity.
Intent serviceIntent = new Intent(this, UserAvailabilityService.class);
startService(serviceIntent);
public class UserAvailabilityService extends Service {
private static final String TAG = UserAvailabilityService.class.getSimpleName();
boolean isChecked = false;
boolean isUserAvailable = false;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate()");
isChecked = getAvailableStatusFromFref();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand()");
return START_NOT_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(TAG, "onTaskRemoved()");
if(isChecked) {
//Hit a api
}
else
{
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}
#Override
public void onLowMemory() {
super.onLowMemory();
Log.i(TAG, "onLowMemory()");
}
}
If app crashes or closed from task manager then that time i want to hit api.
Right Now, When i am swipping the app from background this onTaskRemoved method is calling. and i am hitting the api.
But when i am closing the same app from task manager (Setting->Apps->App name->Force Stop) then this onTaskRemoved method is not calling.
Any idea,please let me know.
Not possible. You cannot tell from within an app whether the app will be terminated. You could watch for termination from a second app, but at any time the first can be closed without notice. Not to mention the variety of ways that both apps could be shut down (for example, they could just pull the battery). You should never write code that requires you to do something on shutdown, because it will never be reliable.
The best you can do is calling isFinishing() which checks if it is being destroyed from you onPause() method
#Override
protected void onPause(){
super.onPause();
if(isFinishing){
callApi();
}
}
Run a service in background continuously. For example, a service has to be kicked off which will display a toast message 20 seconds once even if the app is closed.
public class AppService extends IntentService {
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
public AppService() {
super("AppService");
}
#Override
protected void onHandleIntent(Intent workIntent) {
Toast.makeText(getApplicationContext(), "hai", Toast.LENGTH_SHORT).show();
SystemClock.sleep(20000);
}
}
Below code works for me...
public class AppService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
}
Accepted answer will not work on from Android 8.0 (API level 26), see the android's background limitations here
Modification in Accepted Answer:
1: You have to invoke the service's startForeground() method within 5 seconds after starting the service. To do this, you can call startForeground() in onCreate() method of service.
public class AppService extends Service {
....
#Override
public void onCreate() {
startForeground(9999, Notification())
}
....
}
2: You must call startForegroundService() instead of startService() by checking API level from where you want to start the service.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
This code work for me..
public class ServiceClass extends Service {
public static final int notify = 300000; //interval between two services(Here Service run every 5 Minute)
private Handler mHandler = new Handler(); //run on another Thread to avoid crash
private Timer mTimer = null; //timer handling
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
if (mTimer != null) // Cancel if already existed
mTimer.cancel();
else
mTimer = new Timer(); //recreate new
mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify); //Schedule task
}
#Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel(); //For Cancel Timer
Log.d("service is ","Destroyed");
}
//class TimeDisplay for handling task
class TimeDisplay extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d("service is ","running");
}
});
}
}
}
In your manifest, where you declare your service, add:
android:process=":processname"
This lets the service run on a separate process and thus it will not be killed with the app.
You can then chose if you want to use foreground. It will show a persistent notification, but reduces the likelihood if the service being killed.
Further, if you want to create a continuously running service, use Service, NOT IntentService. IntentService stops when it is finished doing its action.
For a demo I print a Toast after Evert 10 sec. using Service class.
It works fine, I'm getting the Toast after every 10 sec if I am on the Activity when I leave the app, Service is not giving the o/p.
But I want to that toast either I'll kill the App or back press Here is code snippet :
ServiceDemo.java
public class ServiceDemo extends Activity {
private Handler myHandler = new Handler();
private Runnable drawRunnable = new Runnable() {
#Override
public void run() {
as();
myHandler.postDelayed(this, 10000);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service_demo);
myHandler.postDelayed(drawRunnable, 10000);
startService(new Intent(this, MyService.class));
}
public void as(){
startService(new Intent(this, MyService.class));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Service.java
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "HOHO Service Created...", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
}
}
Edit 1
moveTaskToBack(true);
I put this into the onBackPressed method I Service give the o/p if I am not on the screen but When I kill the App, Service not responding
I think you need to override onStartCommand instead of onStart()
like:
public int onStartCommand(Intent intent, int flags, int startid)
{
Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
i think AlarmManager is what you want.
You have to user AlarmManager, here's an example : Alarm Manager Example
Your task will be executed even if the application is terminated.
But if the application is killed by the user, the Alarm will be canceled. See this discussion How to create a persistent AlarmManager
Hi friends i have a one problem to solve...I want to destroy the service completely, once i call onDestroy() method from Activity. But my problem is that i am unable to destroy it completely.. in background its keep on running, i am sharing the sample code what i tried..
//Activity Class
public class ServiceToAct extends Activity {
private static final String TAG = "BroadcastEvent";
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this, BroadcastService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(myService.BROADCAST_ACTION));
}
/*#Override
protected void onResume() {
super.onResume();
}*/
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
#Override
protected void onDestroy() {
stopService(intent);
Toast.makeText(this, "Destroy Completely", Toast.LENGTH_LONG).show();
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
}
// service class
public class myService extends Service {
private static final String TAG = "BroadcastEvent";
public static final String BROADCAST_ACTION = "com.service.activity.myService";
private final Handler handler = new Handler();
Intent intent;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "created", Toast.LENGTH_LONG).show();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "start", Toast.LENGTH_LONG).show();
handler.removeCallbacks(sendToUI);
handler.postDelayed(sendToUI, 1000);
}
#Override
public void onDestroy() {
super.onDestroy();
stopSelf();
//stopService(intent);
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
private Runnable sendToUI = new Runnable() {
#Override
public void run() {
myData();
handler.postDelayed(this, 10000);
}
};
private void myData() {
Log.d(TAG, "keep on entering");
Toast.makeText(this, "Keep on despling in UI", Toast.LENGTH_LONG).show();
sendBroadcast(intent);
}
}
Here Actually i want to update my UI from service, Mine everything is working, but if i destroy the service its keep on calling myData() method, and i am getting the Toast msg if i close the application also.
My issue is i don't want that toast msg once the service is desroyed
I used stopService(intent) method, which destroy the service, but background method myData() is keep on calling
for stop service completely use this ..
myActivity.java
#Override
public void onDestroy() {
stopService(intent);
super.onDestroy();
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
service.java
#Override
public void onDestroy()
{
stopSelf();
super.onDestroy();
}
You'd better never call onXxx() derectly.
Use stopService(Intent i) in your activity and stopSelf() in you service to stop instead.
use stopService() method after updating UI
or
Instead of using startService use bindService in the activity. When activity destroys, service also destroys
I need to call TTS service within subclass of BroadcastReceiver. When I am implement that class from OnInitListener, it gave run-time error.
Is there any other-way to implement TTS within BroadcastReceiver?
Thank You,
Sorry Code:
public class TextApp extends BroadcastReceiver implements OnInitListener {
private TextToSpeech tts;
private String message = "Hello";
#Override
public void onReceive(Context context, Intent intent) {
tts = new TextToSpeech(context, this);
message = "Hello TTS";
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS)
{
tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
Your code didn't work on :
tts = new TextToSpeech(context, this);
Context on BroadcastReceiver is a "restricted context". It means you cannot start service on context in BroadcastReceiver. Because TTS is a service, so it doesn't call anyting.
The Best Solutions is you start another intent on BroadcastReceiver with activity that call the service.
public void onReceive(Context context, Intent intent) {
....
Intent speechIntent = new Intent();
speechIntent.setClass(context, ReadTheMessage.class);
speechIntent.putExtra("MESSAGE", message.getMessageBody().toString());
speechIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(speechIntent);
....
}
And then on the activity you call the TTS service with parameter from extras
public class ReadTheMessage extends Activity implements OnInitListener,OnUtteranceCompletedListener {
private TextToSpeech tts = null;
private String msg = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent startingIntent = this.getIntent();
msg = startingIntent.getStringExtra("MESSAGE");
tts = new TextToSpeech(this,this);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (tts!=null) {
tts.shutdown();
}
}
// OnInitListener impl
public void onInit(int status) {
tts.speak(msg, TextToSpeech.QUEUE_FLUSH, null);
}
// OnUtteranceCompletedListener impl
public void onUtteranceCompleted(String utteranceId) {
tts.shutdown();
tts = null;
finish();
}
}
You can try using either JobIntentService (Post Android-O) or IntentService to invoke TTS from Broadcast receiver. It has less overhead than launching an activity for the sake of giving TTS a correct context. Note that you cannot give a broadcast receiver's context to TTS.
Here is my code snippet where I acheived same thing using JobIntentService.
Inside your custom Broadcast receiver's onReceive() invoke your custom JobIntentService like this:
Intent speechIntent = new Intent();
speechIntent.putExtra("MESSAGE", "Bluetooth is on.");
MySpeakService.enqueueWork(context, speechIntent);
And MySpeakService.java is this:
import android.content.Context;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;
public class MySpeakService extends JobIntentService {
private TextToSpeech mySpeakTextToSpeech = null;
private boolean isSafeToDestroy = false;
public static void enqueueWork(Context context, Intent intent) {
enqueueWork(context, MySpeakService.class, 1, intent);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
String message = intent.getStringExtra("MESSAGE");
mySpeakTextToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
mySpeakTextToSpeech.speak(message, TextToSpeech.QUEUE_ADD, null, null);
while (mySpeakTextToSpeech.isSpeaking()) {
}
isSafeToDestroy = true;
}
});
}
#Override
public void onDestroy() {
if (isSafeToDestroy) {
if (mySpeakTextToSpeech != null) {
mySpeakTextToSpeech.shutdown();
}
super.onDestroy();
}
}
}
Al Zil answer is not totally correct. Android TTS is a bounded service. Broadcast receivers truly has a limited context but they can't bind themselves to any service. However, they can START a service. Starting the tts from activity is ok, but if you don't need UI you can also initialize it from a service. Look at this answer to see how it's done
Good luck.