So I'm calling my intent service on alarm manager but that intent service does not work after my app get crashed.
Is it possible for intent service to not work after your app get crashed?
Thank You.
Is it possible for intent service to not work after your app get
crashed?
You shall catch the crash event with an uncaught exception handler and then cancel the alarm something like below,
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
if (myAlarmMgr!= null) {
myAlarmMgr.cancel(myIntentServiceInstance);
}
}
});
Related
I'm trying to make app close when some uncaughtException happens, but android show a message to try to restart the application and the application stays in slow motion or just black screen, I made a class to extends in my activity to overriding the method uncaughtException() to catch logs to send than to sentry.io and using:
public class MyExceptionHandler implements
Thread.UncaughtExceptionHandler {
public MyExceptionHandler(Activity context) {
Thread.setDefaultUncaughtExceptionHandler(this);
}
#Override
public void uncaughtException(final Thread thread, final Throwable ex) {
Log.e("ERROR", ex.toString());
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}
You can use
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Got idea from this answer.
I am trying to explore the world of Services in Android and I just wrote a small example where the activity has a button that triggers a notification.
The steps I do are:
Creating Intent intent = new Intent(context, MyService.class);
Inserting this in a PendingIntent and sending it to the NotificationManager
Then, once I click on the notification, the service (MyService) is started and launches a music soundtrack.
Using logging I saw that the click of the button and the actions of MyService both happen on the main thread, and I would like to know how can I make the service run in a separate background thread
p.s. MyService is extending Service and not IntentService because this last one terminates once executed
onStartCommand() is called on the main thread in your Service. If you want to launch a background Thread to do the work, you can just create your own Thread and start it inside onStartCommand(). Something like this:
Thread t = new Thread(new Runnable() {
public void run() {
// Put whatever code you want to run in background thread here
}
}).start();
Make sure that you have code that will shutdown running background threads if necessary when your Service needs to stop.
Have you ever work with RXjava?
1-get the librery:
Write these two lines in the build.gradle:
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.2'
2-Write these lines in onStartCommand:
io.reactivex.Observable.just(s).subscribeOn(AndroidSchedulers.mainThread())
.observeOn(Schedulers.io())
.subscribe(new io.reactivex.Observer<String>() {
#Override
public void onSubscribe(#NonNull Disposable d) {
}
#Override
public void onNext(#NonNull String s) {
//Write what you want here!! ;)
}
#Override
public void onError(#NonNull Throwable e) {
}
#Override
public void onComplete() {
}
});
and inside onNext write what ever you want, and it will execute on background thread
I hope it will be helpful
I am having problem with my android IntentService. When I first open the application, the service gets started by intent from the profile activity and data is fetched from this service. If I switch to other activity and then back service is still running and that is ok.
However if you press back, so that activity is finished and put in the background, the service is still working as the application is in background but If I get it back to foreground service stops. I do not know why. Bellow is my code, please help.
I have read activity life cycle couple of times and still do not get it why this is happening.
What is weird is that Service receive data one more time before it stops when MainActivity is brought back to running state. Service is not crashing.
Service
public class SomeService extends IntentService
{
public static final String extra = "someData";
public SomeService()
{
super(SomeService.class.getSimpleName());
}
#Override
protected void onHandleIntent(Intent intent)
{
Log.e("SomeService", "starting service");
while (true)
{
SomeData data = Api.getNewSocketData();
//Broadcast data when received to update the view
Intent broadcastData = new Intent();
broadcastData.setAction(dataBroadcastReceiver.ACTION_DATA_RECEIVED);
broadcastData.addCategory(Intent.CATEGORY_DEFAULT);
broadcastData.putExtra(extra, " ");
sendBroadcast(broadcastData);
Log.e("SomeService", "received from socket");
}
}
}
Receiver
public class dataBroadcastReceiver extends BroadcastReceiver
{
public final static String ACTION_DATA_RECEIVED = "net.bitstamp.intent.action.ACTION_SOMEDATA_RECEIVED";
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("receiver", "data received");
}
}
Main Activity
#Override
public void onPause()
{
super.onPause();
unregisterReceiver(dataBroadcastReceiver);
}
#Override
public void onResume()
{
super.onResume();
IntentFilter intentFilter = new IntentFilter(dataBroadcastReceiver.ACTION_DATA_RECEIVED);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
dataBroadcastReceiver = new dataBroadcastReceiver();
registerReceiver(dataBroadcastReceiver, intentFilter);
Intent someService = new Intent(this, SomeService.class);
startService(someService);
}
I really need help on this. Thanks
You don't want to the up the IntentService in an infinite loop. It will block all other incoming requests. From the documentation:
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
Your Service is likely still happily running along, it just isn't processing your new request because your old one is still being handled in the infinite loop.
I am starting and stopping a service from an activity calling startSertice()/stopService() (when user select/deselect a check box and service is not bounded). Every thing is working fine even though the activity that starts the service is closed. In "Running apps" I'm able to see 1 processes, 1 service running. But when I kill the application, using Task manager kind of application, the process is getting killed and service is not working though the running apps showing 0 processes, 1 service. How to make the service working in such situations? I observed the same in some other security applications like Avast with 0 processes, 1 service, while service working properly. Please help me out on this.
Following is the activity on click method
#Override
public void onClick(View arg0) {
boolean value = checkBox.isChecked();
if(value){
// start the service
startService(new Intent(this, MyService.class));
Toast.makeText(this, "Background service started", Toast.LENGTH_SHORT).show();
} else {
stopService(new Intent(this, MyService.class));
Toast.makeText(this, "Background service stopped", Toast.LENGTH_SHORT).show();
}
}
Following is the service class:
public class MyService extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate(){
super.onCreate();
Log.d("######Service","Service created successfully");
}
#Override
public int onStartCommand(Intent intent, int flags, int stardId){
Log.d("######Service","Service started successfully");
IntentFilter powerButtonIntentFilter = new IntentFilter();
powerButtonIntentFilter.addAction("android.intent.action.SCREEN_ON");
this.registerReceiver(pbReceiver, powerButtonIntentFilter);
Log.d("#######","Power button register registered");
return START_STICKY;
}
#Override
public void onDestroy(){
Log.d("######Service","Service destroyed successfully");
this.unregisterReceiver(pbReceiver);
Log.d("#######","Power button register un-registered");
super.onDestroy();
}
}
Everything is working fine in ideal case. SCREEN ON action is being listened by the broadcast receiver properly even when the activity that starts the service is closed. I am able to see the app running in settings. But when I force kill the process using Task Manager kind of applications, processes is getting killed and in running apps I am able to see 0 process, 1 service running. Though the service is running after force killing the app from Task manager, broadcast receiver is not listening to the SCREEN ON action. Please help me out on this.
Thanks, JK
I have an Android application where I implement a Service which interacts with some hardware over a Bluetooth serial connection. The setup of this connection is slow, so I decided to keep the service in the foreground, so if/when you want to view another application, the connection is ready to go (pseudocode follows):
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
start();
return (START_STICKY);
}
#Override
public void onDestroy() {
stop();
}
start() and stop() are private methods which start communication with the hardware, and in start's case, creates a Notification for use in startForeground() My Activity will call
#Override
public void onStart() {
super.onStart();
// Start the service
Intent intent = new Intent(getApplicationContext(), MyService.class);
ComponentName theService = startService(intent);
//this is to register the functions I need to handle functions my Activity calls
// to the service
bindService(intent, svcConn, BIND_AUTO_CREATE);
}
#Override
public void onStop() {
super.onStop();
if (theService != null) {
unbindService(svcConn);
theService = null;
if (isFinishing()) {
stopService(new Intent(getApplicationContext(), MyService.class));
}
}
}
I've had to add a "Quit" menu item to make sure that the Service shuts down. Worse, if my app crashes, I have to go in and manually kill the Service. Is there a way to elegantly kill the Service if things go horribly wrong, or am I abusing the purpose of a Service, and should find an alternative method of doing what I'd like to do?
Perhaps you can add a hook for your application's main thread(UI thread) for crash, see below:
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
//Kill the service.
}
});
throw new RuntimeException("Uncaught Exception");