Showing posts with label service. Show all posts
Showing posts with label service. Show all posts

Wednesday, September 19, 2018

Problems with Impersonated Service and Network Locations

Leave a Comment

I have a windows service that polls a user selected directory for new files.When a Network location is selected (a folder on a remote machine on the same network),i query the user for the username and password of the remote machine (user who has access to the folder),i validate the same and store it to the registry for the service.This approach works fine.(service runs as localmachine and uses impersonation code).

But there are some scenarios that im unaware of ..

1. Wireless HDDs /Storage devices that are directly connected to the network.Currently i use impersonation code to supply user credentials.In such scenarios will the drive be directly accessible to the service running as localmachine?

2. How to deal with Domain Users who has access to the Folder?

I'm using the following code to impersonate a user

https://stackoverflow.com/a/9213965/848968

UserImpersonation impersonator = new UserImpersonation(); impersonator.impersonateUser("username", "", "password"); //No Domain is required 

What to do in case of domain users?

1 Answers

Answers 1

  1. Wireless HDDs /Storage devices that are directly connected to the network.Currently i use impersonation code to supply user credentials.In such scenarios will the drive be directly accessible to the service running as localmachine?

How is the drive connected to? If its SMB via UNC paths, that should be fine. When you get into mapped drives, those are not available to the windows service.

  1. How to deal with Domain Users who has access to the Folder?

impersonator.impersonateUser("username", "domain", "password");

You may also want to check out this answer for more impersonation information and sample code. There's a great library that wraps this up for you.

Read More

Friday, June 29, 2018

why my widget broadcast receiver service stops when the main app stops

Leave a Comment

I have a widget that implements a specific broadcast receiver service to detect when the wifi connection goes down.

It works perfectly if the main activity is running or not.

The issue I have is when I stop the main activity then the broadcast receiver service stops as I don't detect anymore the wifi changes.

Is there a way to startservice that survives the main activity?

if not, any other mechanisms?

2 Answers

Answers 1

Probably you need to register your receiver in manifest and mark it as exported=true, so it can work if the app is not running. Check this link for detailed info please https://developer.android.com/guide/components/broadcasts

Answers 2

Why have I been down voted?

I've found a workaround: Broadcast Receivers started in an alarm manager are not stopped (when the main activity stops) in O. So I start an AM with a high repeatin interval.

Read More

Thursday, April 19, 2018

Starting a service when the device's screen is unlocked in Android

Leave a Comment

I would like to run my service when the screen is unlocked and stop it when the screen is locked. I looked into these answers and implemented them. However, when I lock my screen the service stops as required, but when I unlock the screen it doesn't starts again.

The code for to run this service is as follows:

public class PhonePositionService extends Service { @Override     public void onCreate() {     //ADDED CODE     IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);     filter.addAction(Intent.ACTION_SCREEN_OFF);     BroadcastReceiver mReceiver = new BootCompletedIntentReceiver();     registerReceiver(mReceiver, filter);     {...}     } @Override     public int onStartCommand(Intent intent, int flags, int startId) {     int icon = R.drawable.ic_stat_bright;     startForeground(NOTIFICATION_ID, getCompatNotification(icon));     if (backgroundThread != null) {       backgroundThread.start();     }     return START_STICKY;   } } 

In some other file, my broadcast receiver code is as follows:

public class BootCompletedIntentReceiver extends BroadcastReceiver {  @Override  public void onReceive(Context context, Intent intent) {    String action = intent.getAction();    if(Intent.ACTION_SCREEN_ON.equals(action)) {      // start the service      Intent pushIntent = new Intent(context, PhonePositionService.class);      context.startService(pushIntent);    } else if(Intent.ACTION_SCREEN_OFF.equals(action)) {      // stop the service      Intent pushIntent = new Intent(context, PhonePositionService.class);      context.stopService(pushIntent);    }   if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {     Intent pushIntent = new Intent(context, PhonePositionService.class);     context.startService(pushIntent);   }  } } 

Then why is it so that when I unlock my phone the service does not start again?

2 Answers

Answers 1

First of all its not possible to detect if user has unlocked the phone until you have Admin Privilages. The issue you are facing is because you are stopping the PhonePositionService using stopService() when Screen is OFF:

public class BootCompletedIntentReceiver extends BroadcastReceiver {  @Override  public void onReceive(Context context, Intent intent) {    String action = intent.getAction();    if(Intent.ACTION_SCREEN_ON.equals(action)) {      // start the service      Intent pushIntent = new Intent(context, PhonePositionService.class);      context.startService(pushIntent);    } else if(Intent.ACTION_SCREEN_OFF.equals(action)) {      // stop the service      Intent pushIntent = new Intent(context, PhonePositionService.class);      //This will stop the service      context.stopService(pushIntent);    }   if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {     Intent pushIntent = new Intent(context, PhonePositionService.class);     context.startService(pushIntent);   }  } } 

It would lead to some memory leak since BroadcastReceiver is not unregistered.

It is discouraged to keep service running in foreground for forever since it could lead to (fast) battery drainage.

I would recommend you to find other alternatives. But if your core functionality is impacted and you still want to proceed you can do following work around:

Make BootCompletedIntentReceiver as inner class for PhonePositionService. And instead of starting and stopping the service you perform your action directly.

public class PhonePositionService extends Service {    @Override    public void onCreate() {        //ADDED CODE        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);        filter.addAction(Intent.ACTION_SCREEN_OFF);        BroadcastReceiver mReceiver = new BootCompletedIntentReceiver();        registerReceiver(mReceiver, filter);        ...     }     ...     private class BootCompletedIntentReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {          String action = intent.getAction();          if(Intent.ACTION_SCREEN_ON.equals(action)) {           //DO action for SCREEN_ON          } else if(Intent.ACTION_SCREEN_OFF.equals(action)) {           //Do action for SCREEN_OFF          }         }    } } 

Answers 2

That's because you are registering your receiver inside your service, which is a component like an activity that has a lifecycle and when it's destroyed your broadcast listener goes with it too. Actually I'm guessing you are leaking your Service here too, because you didn't unregister it which is another problem.

Since API 26 aka Oreo you cannot register you broadcast listener inside AndroidManifest.xml, If you want to target API 26+ your best bet is to register it in your Application class, but be aware when the system kills your app you will lose your broadcast listener too. However if you use a foreground service the system won't kill your service.

Edit: Here is an example:

import android.app.Application; import android.content.Intent; import android.content.IntentFilter;  /**  * @author : M.Reza.Nasirloo@gmail.com  * Created on: 2018-04-12  */ public class App extends Application {      @Override     public void onCreate() {     super.onCreate();     IntentFilter filter = new IntentFilter();     filter.addAction(Intent.ACTION_SCREEN_OFF);     filter.addAction(Intent.ACTION_SCREEN_ON);     registerReceiver(new BootCompletedIntentReceiver(), filter);     } } 

Don't forget to set this class inside your manifest file.

<application     android:name=".App"     android:allowBackup="true" 

Note you need a foreground service to be run always to not miss the events.

PS: There's another solution which is a bit hacky, target a lower API version and register your listener inside the manifest file.

Looks like targeting a lower API is out of table. It seems google knew some developers would use it to get around this.

Read More

Monday, February 5, 2018

What could cause a Java ScheduleService to not run?

Leave a Comment

In my Java application I define a ScheduleService like this:

ScheduledService<Void> scheduledService = new ScheduledService<Void>() {     @Override     protected Task<Void> createTask() {         return new Task<Void>() {             @Override             protected Void call() {                tick();                return null;             }         };     }  }; scheduledService.setPeriod(new javafx.util.Duration(TICK_PERIOD.toMillis())); scheduledService.start(); 

When I trigger the application from IntelliJ it works fine and tick() runs every second. When the application is packaged as an .exe using the JavaFX Packager, the service is never started.

The state of the server after I run .start() in all cases is SCHEDULED. Any ideas what else might be going on? Could something be preventing the creation of threads? Or maybe it's not switching between various threads?

The documentation for ScheduledService says (emphasis mine):

Timing for this class is not absolutely reliable. A very busy event thread might introduce some timing lag into the beginning of the execution of the background Task, so very small values for the period or delay are likely to be inaccurate. A delay or period in the hundreds of milliseconds or larger should be fairly reliable.

Is it possible there's some issue with the event thread? Is there a way to inspect it?

After calling start(), scheduleService.getExecutor() returns null. Is that expected?

I tried setting my own executor defined this way:

BlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(32, Integer.MAX_VALUE, 1000, TimeUnit.MILLISECONDS, blockingQueue); scheduledService.setExecutor(threadPoolExecutor); 

and then I print it out before and after calling start. Before it looks like this:

java.util.concurrent.ThreadPoolExecutor@4d97d155[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] 

and afterwards:

java.util.concurrent.ThreadPoolExecutor@4d97d155[Running, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0] 

So, it is claiming there's an active thread, even though it doesn't seem to be active at all.

Update: I removed the mention of a screensaver because I manage to reproduce the issue as a simple .exe but I still have the problem that the problem doesn't happen when running it from IntelliJ, it only happens when packaged as an .exe.

1 Answers

Answers 1

I found the solution and it had nothing to do with ScheduleService. There were literally three other bugs in my app that were compounding to produce the unexpected behavior as well as hide my attempts at exploring the problem.

Read More

Tuesday, November 14, 2017

Start activity from service takes too long

Leave a Comment

I have a Service that when one function gives to me true it will start a new Activity but it takes like 5 seconds...

I've read about this issue, and I've found on StackOverflow this example to "avoid" this bug..

Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); try {    pendingIntent.send(); } catch (PendingIntent.CanceledException e) {    e.printStackTrace(); } 

but sadly it doesn't start the Activity faster, I don't need to be inmmediate (better if it's possible), but I don't want to wait +5 seconds to launch the new Activity, do you knwo any trick to avoid this?

I'm using PendingIntent because I've found that guy that said that it should solve this issue : Starting an activity from a service after HOME button pressed without the 5 seconds delay

Note

If I press back button it launch it autommatically, 0 delay, but I'm looking pressing the home button.

2 Answers

Answers 1

I cannot comment everywhere yet, so I'm putting this solution of a similar problem as an answer

After much digging, found out the cause of the problem. Apparently it's not a bug, it is a feature which does not allow Services or BroadcastReceivers to launch activities for up to 5 seconds after home button is pressed. No easy way to overcome this.

More info here: https://code.google.com/p/android/issues/detail?id=4536

I replaced the activity with a Window added to the window manager of the running service. This does not cause any delay.

Source link Stackoverflow

Answers 2

First thing we cannot update any UI related stuff in service, neither calling activity nor updating any UI elements, 
Same problem i too have faced.

Then i have used EventBus library to communicate UI elements from service 
Below is the sample example

public class SendSPLocationService extends Service { Handler mHandler = new Handler(); Thread downloadThread; boolean isRunning = true; private VolleyHelper volleyHelper;  @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();     volleyHelper = new VolleyHelper(this);  }  @Override public int onStartCommand(Intent intent, int flags, int startId) {     final Timer t = new Timer();     t.schedule(new TimerTask() {         @Override         public void run() {             Log.d("run: ", "service is running!");              try {                                         EventBus.getDefault().post(new FutureJobEvent(false, error.networkResponse.statusCode, errorJson.getString("message")));              } catch (JSONException e) {                 e.printStackTrace();             }             // t.cancel();             Log.d("run: ", "service is stopped!");          }     }, 0, 5000);     return START_STICKY; } } 

Use below code for triggered event to observe..either in activity/fragment

@Override public void onStart() {     super.onStart();     if (!EventBus.getDefault().isRegistered(this))         EventBus.getDefault().register(this); }  @Override public void onStop() {     super.onStop();     if (EventBus.getDefault().isRegistered(this))         EventBus.getDefault().unregister(this); }  @Subscribe(threadMode = ThreadMode.MAIN)  public void onMessageEvent(TrackSPEvent event) {     if (event.success) {          startActivity(new Intent(this,MainActivity.class));  }  } 
Read More

Wednesday, January 4, 2017

Accessing WCF service via HTTP

Leave a Comment

I wrote a very simple WCF project in Visual Studio:

IBookStore:

using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web;  namespace BookStore {     [ServiceContract]     public interface IBookStore     {         [OperationContract]         [WebGet]         List<Book> GetBooksList();          [OperationContract]         [WebGet(UriTemplate = "GetBook/{id}")]  // The value of UriTemplate defines the name that the                                                 // client should use to turn to the function         Book GetBookById(int id);          [OperationContract]         [WebInvoke(UriTemplate = "AddBook/{name}", Method = "PUT")]         void AddBook(string name);          [OperationContract]         [WebInvoke(UriTemplate = "UpdateBook/{id}/{name}", Method = "POST")]         void UpdateBook(int id, string name);          [OperationContract]         [WebInvoke(UriTemplate = "DeleteBook/{id}", Method = "DELETE")]         void DeleteBook(int id);     }       [DataContract]     public class Book     {         int id;         string name;           [DataMember]         public int ID         {             get { return id; }             set { id = value; }         }          [DataMember]         public string Name         {             get { return name; }             set { name = value; }         }     } } 

BookStoreImpl:

using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Activation;  namespace BookStore {     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]     [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]     public class BookStoreImpl : IBookStore     {         public void AddBook(string name)         {             using (var db = new BookStoreContext())             {                 Book book = new BookStore.Book { Name = name };                 db.Books.Add(book);                 db.SaveChanges();             }         }          public void DeleteBook(int id)         {             try             {                 using (var db = new BookStoreContext())                 {                     Book book = db.Books.Find(id);                     db.Books.Remove(book);                     db.SaveChanges();                 }             }             catch             {                 throw new FaultException("Something went wrong");             }         }          public Book GetBookById(int id)         {             using (var db = new BookStoreContext())             {                 return db.Books.Find(id);             }         }          public List<Book> GetBooksList()         {             List<Book> allBooks = new List<Book>();             try             {                 using (var db = new BookStoreContext())                 {                     IEnumerator<Book> booksEnum = db.Books.GetEnumerator();                     booksEnum.Reset();                     while (booksEnum.MoveNext())                     {                         allBooks.Add(booksEnum.Current);                     }                 }             }             catch             {                 throw new FaultException("Something went wrong");             }             return allBooks;         }          public void UpdateBook(int id, string name)         {             try             {                 using (var db = new BookStoreContext())                 {                     Book book = db.Books.Find(id);                     book.Name = name;                     db.SaveChanges();                 }             }             catch             {                 throw new FaultException("Something went wrong");             }         }     } } 

My WebConfig file is:

<?xml version="1.0" encoding="utf-8"?> <configuration>   <configSections>     <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />   </configSections>   <appSettings>     <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />   </appSettings>   <system.web>     <compilation debug="true" targetFramework="4.5.2" />     <httpRuntime targetFramework="4.5.2" />     <httpModules>       <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />     </httpModules>   </system.web>    <system.serviceModel>          <behaviors>         <serviceBehaviors>             <behavior name="MyServiceBehavior">                 <serviceMetadata httpGetEnabled="true"    />                 <serviceDebug includeExceptionDetailInFaults="true"/>                       </behavior>         </serviceBehaviors>       <endpointBehaviors>         <behavior name="WebBehavior">           <webHttp />         </behavior>       </endpointBehaviors>     </behaviors>         <services>             <service behaviorConfiguration="MyServiceBehavior" name="BookStore.BookStoreImpl">         <endpoint address="http://localhost:8080/bookservice/" binding="wsHttpBinding" contract="BookStore.IBookStore" />         <endpoint address="" behaviorConfiguration="WebBehavior"                   binding="webHttpBinding"                   contract="BookStore.IBookStore">         </endpoint>         <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>       </service>     </services>       </system.serviceModel>   <!--   <system.serviceModel>     <services>       <service name="BookStore.BookStoreImpl">         <endpoint address="http://localhost:8080/bookservice"             behaviorConfiguration="restfulBehavior" binding="webHttpBinding"             bindingConfiguration="" contract="BookStore.IBookStore"             />         <host>           <baseAddresses>             <add baseAddress="http://localhost:8080/bookservice" />           </baseAddresses>         </host>       </service>     </services>     <behaviors>       <serviceBehaviors>         <behavior>           <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />           <serviceDebug includeExceptionDetailInFaults="false" />         </behavior>       </serviceBehaviors>       <endpointBehaviors>         <behavior name="restfulBehavior">           <webHttp />         </behavior>       </endpointBehaviors>     </behaviors>     <protocolMapping>       <add binding="basicHttpsBinding" scheme="https" />     </protocolMapping>     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />   </system.serviceModel>   -->   <system.webServer>     <modules runAllManagedModulesForAllRequests="true">       <remove name="ApplicationInsightsWebTracking" />       <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />     </modules>     <!--         To browse web app root directory during debugging, set the value below to true.         Set to false before deployment to avoid disclosing web app folder information.       -->     <directoryBrowse enabled="true" />     <validation validateIntegratedModeConfiguration="false" />   </system.webServer>   <entityFramework>     <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">       <parameters>         <parameter value="mssqllocaldb" />       </parameters>     </defaultConnectionFactory>     <providers>       <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />     </providers>   </entityFramework> </configuration> 

I have also created the database, attached it to the project with the .mdf file, compiled and run the project and I can see the timer running in the right corner of the screen after I run the project. Then I open my browser, type into the address box: http://localhost:8080/bookservice/GetBooksList and press enter and I get an error page instead. Doesn't look like my requests ever get to the server in the first place. Can anyone please help me understand why?

Here's the error: enter image description here

EDIT: I noticed that if I set a breakpoint somewhere and run, I see the following error in the "WCF Test Client" window that pops up: "Error: Cannot obtain Metadata from http://localhost:59250/BookStoreImpl.svc If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error URI: http://localhost:59250/BookStoreImpl.svc Metadata contains a reference that cannot be resolved: 'http://localhost:59250/BookStoreImpl.svc'. The requested service, 'http://localhost:59250/BookStoreImpl.svc' could not be activated. See the server's diagnostic trace logs for more information.HTTP GET Error URI: http://localhost:59250/BookStoreImpl.svc There was an error downloading 'http://localhost:59250/BookStoreImpl.svc'. The request failed with the error message:-- No protocol binding matches the given address 'http://localhost:8080/bookservice/'. Protocol bindings are configured at the Site level in IIS or WAS configuration. body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt} .marker {font-weight: bold; color: black;text-decoration: none;} .version {color: gray;} .error {margin-bottom: 10px;} .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } @media screen and (max-width: 639px) { pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; } } @media screen and (max-width: 479px) { pre { width: 280px; } }

Server Error in '/' Application.

No protocol binding matches the given address 'http://localhost:8080/bookservice/'. Protocol bindings are configured at the Site level in IIS or WAS configuration.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: No protocol binding matches the given address 'http://localhost:8080/bookservice/'. Protocol bindings are configured at the Site level in IIS or WAS configuration.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:

[InvalidOperationException: No protocol binding matches the given address 'http://localhost:8080/bookservice/'. Protocol bindings are configured at the Site level in IIS or WAS configuration.] System.ServiceModel.Activation.HostedAspNetEnvironment.GetBaseUri(String transportScheme, Uri listenUri) +109963 System.ServiceModel.Channels.TransportChannelListener.OnOpening() +13058405 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +265 System.ServiceModel.Channels.DatagramChannelDemuxer2.OnOuterListenerOpen(ChannelDemuxerFilter filter, IChannelListener listener, TimeSpan timeout) +445 System.ServiceModel.Channels.SingletonChannelListener3.OnOpen(TimeSpan timeout) +78 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +61[InvalidOperationException: The ChannelDispatcher at 'http://localhost:8080/bookservice/' with contract(s) '"SecurityNegotiationContract"' is unable to open its IChannelListener.] System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +134 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +136 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Security.NegotiationTokenAuthenticator1.OnOpen(TimeSpan timeout) +137 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) +21 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan timeout) +23 System.ServiceModel.Security.SymmetricSecurityProtocolFactory.OnOpen(TimeSpan timeout) +513 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) +21 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) +86 System.ServiceModel.Channels.SecurityChannelListener1.OnOpen(TimeSpan timeout) +240 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +61[InvalidOperationException: The ChannelDispatcher at 'http://localhost:8080/bookservice/' with contract(s) '"IssueAndRenewSession"' is unable to open its IChannelListener.] System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +134 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +136 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Security.SecuritySessionSecurityTokenAuthenticator.OnOpen(TimeSpan timeout) +129 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) +21 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan timeout) +23 System.ServiceModel.Security.SecuritySessionServerSettings.OnOpen(TimeSpan timeout) +759 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) +21 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) +130 System.ServiceModel.Channels.SecurityChannelListener1.OnOpen(TimeSpan timeout) +240 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +61[InvalidOperationException: The ChannelDispatcher at 'http://localhost:8080/bookservice/' with contract(s) '"IBookStore"' is unable to open its IChannelListener.] System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +134 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +136 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +308 System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +110 System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +641[ServiceActivationException: The service '/BookStoreImpl.svc' cannot be activated due to an exception during compilation. The exception message is: The ChannelDispatcher at 'http://localhost:8080/bookservice/' with contract(s) '"IBookStore"' is unable to open its IChannelListener..] System.Runtime.AsyncResult.End(IAsyncResult result) +481507 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +174 System.ServiceModel.Activation.ServiceHttpModule.EndProcessRequest(IAsyncResult ar) +351314 System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +9791593</pre></code> </td> </tr> </table> <br> <hr width=100% size=1 color=silver> <b>Version Information:</b>ÿMicrosoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1586.0 </font> </body></html><!-- [InvalidOperationException]: No protocol binding matches the given address 'http://localhost:8080/bookservice/'. Protocol bindings are configured at the Site level in IIS or WAS configuration. at System.ServiceModel.Activation.HostedAspNetEnvironment.GetBaseUri(String transportScheme, Uri listenUri) at System.ServiceModel.Channels.TransportChannelListener.OnOpening() at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Channels.DatagramChannelDemuxer2.OnOuterListenerOpen(ChannelDemuxerFilter filter, IChannelListener listener, TimeSpan timeout) at System.ServiceModel.Channels.SingletonChannelListener3.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout)[InvalidOperationException]: The ChannelDispatcher at 'http://localhost:8080/bookservice/' with contract(s) '"SecurityNegotiationContract"' is unable to open its IChannelListener. at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.NegotiationTokenAuthenticator1.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan timeout) at System.ServiceModel.Security.SymmetricSecurityProtocolFactory.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) at System.ServiceModel.Channels.SecurityChannelListener1.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout)[InvalidOperationException]: The ChannelDispatcher at 'http://localhost:8080/bookservice/' with contract(s) '"IssueAndRenewSession"' is unable to open its IChannelListener. at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.SecuritySessionSecurityTokenAuthenticator.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open(TimeSpan timeout) at System.ServiceModel.Security.SecuritySessionServerSettings.OnOpen(TimeSpan timeout) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open(TimeSpan timeout) at System.ServiceModel.Channels.SecurityChannelListener1.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout)[InvalidOperationException]: The ChannelDispatcher at 'http://localhost:8080/bookservice/' with contract(s) '"IBookStore"' is unable to open its IChannelListener. at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity)[ServiceActivationException]: The service '/BookStoreImpl.svc' cannot be activated due to an exception during compilation. The exception message is: The ChannelDispatcher at 'http://localhost:8080/bookservice/' with contract(s) '"IBookStore"' is unable to open its IChannelListener.. at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result) at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) at System.ServiceModel.Activation.ServiceHttpModule.EndProcessRequest(IAsyncResult ar) at System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar)-->--."

2 Answers

Answers 1

Seems like the problem with your WCF hosting.

WCF service should run inside some host. It could be console application, ASP.NET application, windows service, etc.

Before you're trying to access the url http://localhost:8080/bookservice/, have you deployed your service as IIS application with specified address?

Most likely you're just launching your application under debug in Visual Studio. In this case you should check whether Project url is configured correctly. Open Project properties, Web tab. What address is specified in 'Project Url' edit box?

enter image description here

By default VS puts there 'localhost:some random port', e.g.: http://localhost:38577/. And in your case the port is most likely 59250 that is seen from error

Error: Cannot obtain Metadata from http://localhost:59250/BookStoreImpl.svc

If this is the case and you want to stick to your Web.config, then change this value to http://localhost:8080/bookservice/, press 'Create Virtual Directory' and relaunch debug session. Then try to access GetBooksList method again.

Answers 2

To see if basic binding works can you make this change.

<service behaviorConfiguration="MyServiceBehavior" name="BookStore.BookStoreImpl">     <endpoint address=""                behaviorConfiguration="WebBehavior"               binding="basicHttpBinding"               bindingConfiguration="HttpBinding"                   contract="BookStore.IBookStore">     </endpoint>     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> 
Read More

Thursday, April 28, 2016

Accelerometer sensor cause losses running into a service

Leave a Comment

I am developing an application for Android Wear. It consists listen coordinates from accelerometer sensor, and find a pattern.

To do this, when the user clicks a button, the service starts and begins to store coordinates in a List. Usually accelerometer sensor log 4 to 5 coordinates per second.

The problem is sometimes the onSensorChanged() method does not receive data for several seconds, causing losses of data and difficult to find a pattern.

Here is a gist of my service: https://gist.github.com/cpalosrejano/8f0e59e47124275136fc3d5d941faa07

Things I've tried:

  • I am using android:stopWithTask=false to prevent the service stops when the activity dies.
  • I have also used a WakeLock to prevent the device go to sleep while the services is recording coordinates.

What am I doing wrong? Is there another way to receive callbacks from accelerometer sensor without causing lose data?

Thanks for any help.

1 Answers

Answers 1

What you can do is to write the data to a file on the device and read it from the file.

// When sensor value has changed @Override public void onSensorChanged(SensorEvent event){     if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){      //Perform a background task to store the data     new SensorEventLoggerTask().execute(event);      // And continue to do whatever you want and grab the data     // The data will be saved in to a file on the device and read it from themre     } } 
Read More

Monday, April 25, 2016

Bug recording videos android

Leave a Comment

I'm trying to reocord many videos of 30 seconds in background but, after 20 or 30 videos my service wich is stoping and launching the process to record go slowly.

I have try with a service in the same process and the problem was the same.

My video handler:

@Override public void onCreate() {     super.onCreate();     isRunning = true;     idAlerta = Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "");     videoCount = 1;     mIntentRecorder = new Intent(VideoHandlerService.this, RecorderService.class);     mIntentSend = new Intent(VideoHandlerService.this, SendVideoService.class);     updateVideoTime();     mIntentRecorder.putExtra(Constants.VIDEO_TIME, videoTime);     mIntentRecorder.putExtra(Constants.ID_ALERTA_SERVICE, idAlerta);     mIntentRecorder.putExtra(Constants.COUNT_ALERTA, videoCount);     startService(mIntentRecorder);     newVideo(); } public void newVideo() {     Common.log("new Video");     new Handler().postDelayed(new Runnable() {         @Override         public void run() {             videoCount++;             startNewVideo();             if (videoCount == 2)                 sendVideo(4000);         }     }, videoTime + 2000);  }   public void startNewVideo() {     final Intent intentRecorder = new Intent(VideoHandlerService.this, RecorderService.class);     intentRecorder.putExtra(Constants.VIDEO_TIME, videoTime);     Common.log("idAlerta " + idAlerta);     intentRecorder.putExtra(Constants.ID_ALERTA_SERVICE, idAlerta);     intentRecorder.putExtra(Constants.COUNT_ALERTA, videoCount);     stopService(intentRecorder);     if (Common.getStorage().getBoolean(Constants.RECORDER_ACTIVE, false)) {         if (Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "") != null && Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "").length() > 0) {              new Handler().postDelayed(new Runnable() {                 @Override                 public void run() {                     Common.log("Start service recorder");                     startService(intentRecorder);                     newVideo();                 }             }, 5000);         }     } else         new Handler().postDelayed(new Runnable() {             @Override             public void run() {                 startNewVideo();             }         }, 5000); } 

And this is the process to record:

@Override public int onStartCommand(Intent intent, int flags, int startId) {     Common.log("onStartCommand");     if (intent != null && ((Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "") != null && Common.getStorage().getString(Constants.ID_ALERTA_SERVICE, "").length() > 0))) {         windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);         mLayoutParams = new WindowManager.LayoutParams(                 1, 1,                 WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,                 WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,                 PixelFormat.TRANSLUCENT         );         mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;         //Cojo Información del videohandler         Common.log("Intent distinto de null");         mVideoTime = intent.getIntExtra(Constants.VIDEO_TIME, 15000);         mIdAlerta = intent.getStringExtra(Constants.ID_ALERTA_SERVICE);         mVideoCount = intent.getIntExtra(Constants.COUNT_ALERTA, 1);         Common.log("Video time" + mVideoTime);         Common.getStorage().putBoolean(Constants.RECORDER_ACTIVE, true);         initRecording();     }     return START_NOT_STICKY; }  public void initRecording() {     Common.log("INIT RECORDING IN");     surfaceView = new SurfaceView(this);     windowManager.addView(surfaceView, mLayoutParams);     surfaceView.getHolder().addCallback(this);     Common.log("INIT RECORDING OUT"); }  @Nullable @Override public IBinder onBind(Intent intent) {     return null; }   @Override public void onDestroy() {     Common.log("onDestroy Video");     PreferenceHelper preferenceHelper = PreferenceHelper.newInstance(RecorderService.this, Constants.USER_PREFERENCES);     preferenceHelper.setBoolean(Constants.IS_RECORDING, false);     try {         camera.setPreviewCallback(null);     } catch (Exception e){         Common.log("error setPrevieCallback" + (e.getMessage() != null ? e.getMessage() : "sin mensaje"));     }      try {         muteSounds(false);     } catch (Exception e) {         Common.log(e.getMessage());     }     try {         Common.log("media recorder stop");         mediaRecorder.stop();         Common.log("media recorder reset");         mediaRecorder.reset();         Common.log("media recorder release");         mediaRecorder.release();         Common.log("media camera lock");         camera.lock();         Common.log("media camera release");         camera.release();     } catch (Exception e) {      }      Common.log("onDestroy Video");     Common.getStorage().putBoolean(Constants.RECORDER_ACTIVE, false);     RecorderService.super.onDestroy();     System.exit(0); }   @Override public void surfaceCreated(SurfaceHolder holder) {     mSurfaceHolder = holder;     Common.log("SurfaceCreated");     try {         try {             muteSounds(true);         } catch (Exception e) {             Common.log(e.getMessage());         }         Common.log("CAMERA OPEN 1");         try {             camera = Camera.open(1);         } catch (RuntimeException e) {             Common.log(e.getMessage());         }         Common.log("CAMERA OPEN 2");          ///////////////////////////         mCamCoderProfile = CamcorderProfile.get(1, CamcorderProfile.QUALITY_LOW);         mCamCoderProfile.videoCodec = MediaRecorder.VideoEncoder.MPEG_4_SP;         mCamCoderProfile.audioCodec = MediaRecorder.AudioEncoder.AAC;         ///////////////////////////          startRecorder();      } catch (Exception e) {         if (e.getMessage() != null)             Common.log(e.getMessage());     } }   public void muteSounds(boolean mute) {     Common.log("MUTE SOUNDS IN");     AudioManager mgr = ((AudioManager) getSystemService(Context.AUDIO_SERVICE));     mgr.setStreamMute(AudioManager.STREAM_SYSTEM, true);     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {         if (mute) {             mgr.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_MUTE, 0);             mgr.adjustVolume(AudioManager.ADJUST_MUTE, 0);             mgr.adjustVolume(AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE, 0);         } else {             mgr.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_UNMUTE, 0);             mgr.adjustVolume(AudioManager.ADJUST_UNMUTE, 0);         }     } else {         mgr.setStreamMute(AudioManager.STREAM_SYSTEM, mute);         mgr.setStreamMute(AudioManager.STREAM_MUSIC, mute);         if (mute) {             mOlderVolumen = mgr.getStreamVolume(AudioManager.STREAM_RING);             mgr.setStreamVolume(AudioManager.STREAM_RING, 0, 0);         } else             mgr.setStreamVolume(AudioManager.STREAM_RING, mOlderVolumen, 0);          mgr.adjustVolume(AudioManager.ADJUST_LOWER, 0);     }     Common.log("MUTE SOUNDS OUT"); }   public void startRecorder() {     mediaRecorder = new MediaRecorder();     camera.unlock();     mediaRecorder.setCamera(camera);     mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());     mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);     mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);     mediaRecorder.setProfile(mCamCoderProfile);     videoFile = new File(Environment.getExternalStorageDirectory() + "/" +             "wbunker_" + mIdAlerta + "_" + mVideoCount + ".mp4");     Common.log("Video rercorder name file " + videoRecording);     mediaRecorder.setOutputFile(videoFile.getPath());     mediaRecorder.setOrientationHint(270);     try {         Common.log("mediaRecorder prepare");         mediaRecorder.prepare();         Common.log("mediaRecorder prepare");     } catch (Exception e) {     }     Common.log("mediaRecorder start");     mediaRecorder.start();     Common.log("mediaRecorder start");     Common.log("Estoy grabando macho"); } 

When I try to stop the service the services stops, but the camera isn't released even killing the app. Can someone help me?? thanks in advance.

1 Answers

Answers 1

In the onDestroy() method of your service replace the camera.lock() with camera.unLock() and in the startRecorder() method replace the camera.unLock() with camera.lock()

Read More

Friday, April 1, 2016

Remote Service deny permission onBind

Leave a Comment

I have a remote service, which external applications can bind to. There are situations where I may wish to decline the binding. According to the documentation,

Return the communication channel to the service. May return null if clients can not bind to the service.

@Override public IBinder onBind(final Intent intent) {     return null; } 

Returning null does indeed not return an IBinder object and therefore prevents the connection, however the calling application does not correctly receive this 'information'.

boolean bound = context.bindService(intent, serviceConnection, flagsHere); 

Whether returning null or not from the Service, this always returns true?

According to the documentation,

Returns - If you have successfully bound to the service, true is returned; false is returned if the connection is not made so you will not receive the service object

I had assumed that returning null from onBind would have caused bindService to return false. Assumptions are never a good idea...

Returning null does however prevent the ServiceConnection from being instantiated invoked, but a consequence of this would be no option to check if the binder is in fact null in onServiceConnected.

So, my question - How does an application 'know' if the binding request has been denied?

Additionally, if I decide on the fly that a request to onRebind (having previously returned true from onUnbind) should be declined, I seem to be unable to override the behaviour to prevent this:

@Override public void onRebind(final Intent intent) {      if (shouldAllowRebind(intent)) {         super.onRebind(intent);     } else {         // ?     } } 

I hope someone can shed some light for me. Thanks in advance.

1 Answers

Answers 1

You probably have to create a workaround. I see two options here:

  • Return a Binder without any functionality if the request should be denied. The client then has to check if the wanted functionality is there. (probably with instanceof).
  • Always return the same Binder, but let every method throw an Exception (e.g. SecurityException) if the call is not permitted. (This was also suggested by @CommonsWare in the comments)

I would personnaly prefer the second approach as it is more flexible. (e.g. allows per-call permit/deny, solves the problem of denying stuff after a rebind, etc.)

Read More

Friday, March 25, 2016

EventBus : Activity does not receive event when app is in the background

Leave a Comment

I'm using EventBus to communicate between Activity and Service. Today I got a problem and don't know why.

  1. I have Activity, Fragment and Service. All of them are working fine.

  2. In Activity and Fragment I registered them to Receive events which delivered from Service

  3. In Activity and Fragment, I un-register them when onDestroy() was called.

  4. In normal cases, when Services delivers events, Fragment and Activity can receive those events and work well.

  5. But when App is pushed on the background (by presses Home or Power button), only Fragment receives events which delivered from Service, and Activity does not receive them.

  6. I did not do anything in onPause() both of Activity and Fragment.

Question:

Is there any explanation for that? And how can I make my Activity receives event like Fragment did when app is pushed on background?

4 Answers

Answers 1

When user presses back/home button, Activity can be destroyed anytime and thus you won't be able to receive the data using EventBus. If any how you are trying to receive the data when the Activity is in background, it may leak memory and the app will crash.

There can be other approaches to get the data in the Activity when user resumes the activity.

You can either user sharedpreferences or local database to save the results passed be the service. And when the user navigates back to the activity, read it from sharedpreferences or database.

This way there won't be any issue with memory leakage or data loss.

Edit 1:

It is always recommended to unregister listeners in either onPause or onStop because the activity does not need those events when it is not in the foreground. And since onDestroy() is not guaranteed to be called, thus you could continue receiving broadcasts when the Activity is no longer open.

Answers 2

The Activity class provides two lifecycle methods, onStop() and onRestart() when is not visible (background mode), which allow you to specifically handle how your activity handles being stopped and restarted. Unlike the paused state, which identifies a partial UI obstruction, the stopped state guarantees that the UI is no longer visible and the user's focus is in a separate activity (or an entirely separate app).

In order to understand this cycle, take a look a this image that shows the flow when your app goes out of foreground mode.

When the user leaves your activity

In your case you can handle the issue like this.

  • Provide to the user a mechanism to save persistent application data using either local database(Sqlite), sharedPreferences.
  • Handle your data persistency on onStop() method.
  • When user callback your app, then you will need to restore the data using onRestart() method.

    Here is the way to implement that.

    public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile";  @Override protected void onCreate(Bundle state){    super.onCreate(state);    . . .     // Restore preferences    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);    boolean silent = settings.getBoolean("silentMode", false);    setSilent(silent); }  @Override protected void onStop(){    super.onStop();    // We need an Editor object to make preference changes.   // All objects are from android.context.Context   SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);   SharedPreferences.Editor editor = settings.edit();   editor.putBoolean("silentMode", mSilentMode);    // Commit the edits!   editor.commit(); } 

    }

Please read the following documentation from Android Developer site

Answers 3

It's hard to guess what you have done which causing this behavior, consider providing some code.

But what is obvious is that you have some design flaws.

You must unregister from any event bus or listener in your ui components like Activities or Fragments when user navigates back from the app, if you don't, there is a good chance to leak your activity and all of the resources which it holds.

You should store any data which you receive or calculate in your background service to a file or database, when user open or reopen your app you should check for that data and act on it.

Answers 4

Needs more codes or examples to properly help you. But try the following.

  1. Are your activities extended from a baseActivity? and if so remove the onDestroy eventbus unregister code and check.
  2. In developer options, check whether the don't keep activities option is unchecked.
  3. Pressing back will kill your app anyway unless u have overridden the back event.
Read More