Search Results

Search found 121 results on 5 pages for 'onstart'.

Page 2/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • Is it possible to Kick off a java process under Windows Service with C#?

    - by Wing C. Chen
    I would like to wrap a java program into a windows service with C# using System.ServiceProcess.ServiceBase. So I came up with the following code: /// <summary> /// The main entry point for the application. /// </summary> static void Main() { System.ServiceProcess.ServiceBase.Run(new JavaLauncher()); } protected override void OnStart(string[] args) { Thread _thread; _thread = new Thread(StartService); _thread.Start(); base.OnStart(args); } protected override void OnStop() { Thread _thread; _thread = new Thread(StopService); _thread.Start(); base.OnStop(); } static public void StartService() { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents = false; proc.StartInfo.FileName = "javaw"; proc.StartInfo.Arguments = config.generateLaunchCommand(); proc.Start(); } static public void StopService() { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents = false; proc.StartInfo.FileName = "javaw"; proc.StartInfo.Arguments = "-jar stop.jar"; proc.Start(); } Firstly I had to use Threads in OnStart and OnStop. If not, an exception occurs complaining that the service is terminated because of doing nothing. Secondly, the service can be hooked up to windows smoothly. However, the service terminates a short while after it is started. I looked into the process monitor, only the service process stays alive for that short while, the javaw process never showed up, however. Is there anyone who knows how this can be fixed? It works fine in an ordinary console environment. I think it has something to do with Windows service.

    Read the article

  • setImageViewResource Sometimes loads image and sometimes it doesn't.

    - by Niv
    Hi All, I'm writing a simple widget which has an imageview widget that is supposed to load an image dynamically. To do this, I'm starting a service in the onUpdate method of the service. I validated that the service is running, however, the image is loaded only once every 10 times. Here is the code: (In the Original extends AppWidgetProvider) @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Log.d(LOG_TAG, "onUpdate(): Starting Service..1"); context.startService(new Intent(context, UpdateService.class)); } (The service:) @Override public void onStart(Intent intent, int startId) { Log.d(LOG_TAG, "(OnStart) In On Start..!"); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(this, Original.class)); for (int appWidgetId : appWidgetIds) { RemoteViews remoteView = new RemoteViews(this.getPackageName(), R.layout.widget); remoteView.setImageViewResource(R.id.widgetImage, R.drawable.let02); remoteView.setTextViewText(R.id.widget_textview_month, "aaa"); Log.d(LOG_TAG, "(OnUpdate) Set All Fields!"); appWidgetManager.updateAppWidget(appWidgetId, remoteView); } //super.onStart(intent, startId); return; }

    Read the article

  • Why my tracking service freezes when the phone moves?

    - by user2878181
    I have developed a service which includes timer task and runs after every 5 minutes for keeping tracking record of the device, every five minutes it adds a record to the database. My service is working fine when the phone is not moving i.e it gives records after every 5 minutes as it should be. But i have noticed that when the phone is on move it updates the points after 10 or 20 minutes , i.e whenever the user stops in his way whenever he is on the move. Do service freezes on the move, if yes! how is whatsapp messenger managing it?? Please help! i am writing my onstart method. please help @Override public void onStart(Intent intent, int startId) { Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show(); Log.d(TAG, "onStart"); mLocationClient.connect(); final Handler handler_service = new Handler(); timer_service = new Timer(); TimerTask thread_service = new TimerTask() { @Override public void run() { handler_service.post(new Runnable() { @Override public void run() { try { some function of tracking } }); } }; timer_service.schedule(thread_service, 1000, service_timing); //sync thread final Handler handler_sync = new Handler(); timer_sync = new Timer(); TimerTask thread_sync = new TimerTask() { @Override public void run() { handler_sync.post(new Runnable() { @Override public void run() { try { //connecting to the central server for updation Connect(); } catch (Exception e) { // TODO Auto-generated catch block } } }); } }; timer_sync.schedule(thread_sync,2000, sync_timing); }

    Read the article

  • NET START command not passing parameters in Windows Server 2008

    - by Amanbbk
    My application calls a Stored Procedure, through the stored procedure I am calling a Windows Service using the NET START command as follows: SELECT @Cmd = 'Net Start ServiceName /"' + @param1 + '" /"' + @param2 + '"' Now the parameters passed here are not reaching the OnStart method. These values are blank. Protected Overrides Sub OnStart(ByVal args() As String) Try service1= New Service service1.param2 = args(1) service1.param1 = args(0) Here I get args(0) as the name of service instead of the value that is passed, and args(1) is blank. Although the args.Getlength(0) returns 2. The service starts successfully, it invokes the executable, but the parameters are not there. What can be the reason? Administrative access might be required in NET START command? Has the syntax changed for NET START command in Windows Server 2008? Windows Services do not accept parameters in Windows Server 2008? The same thing is running fine on Windows Server 2003.

    Read the article

  • Running Jetty under Windows Azure Using RoleEntryPoint in a Worker Role

    - by Shawn Cicoria
    This post is built upon the work of Mario Kosmiskas and David C. Chou’s prior postings – from here: http://blogs.msdn.com/b/mariok/archive/2011/01/05/deploying-java-applications-in-azure.aspx  http://blogs.msdn.com/b/dachou/archive/2010/03/21/run-java-with-jetty-in-windows-azure.aspx As Mario points out in his post, when you need to have more control over the process that starts, it generally is better left to a RoleEntryPoint capability that as of now, requires the use of a CLR based assembly that is deployed as part of the package to Azure. There were things I liked especially about Mario’s post – specifically, the ability to pull down the JRE and Jetty runtimes at role startup and instantiate the process using the extracted bits.  The way Mario initialized the java process (and Jetty) was to take advantage of a role startup task configured as part of the service definition.  This is a great quick way to kick off processes or tasks prior to your role entry point.  However, if you need access to service configuration values or role events, that’s where RoleEntryPoint comes in.  For this PoC sample I moved the logic for retrieving the bits for the jre and jetty to the worker roles OnStart – in addition to moving the process kickoff to the OnStart method.  The Run method at this point is there to loop and just report the status of the java process. Beyond just making things more parameterized, both Mario’s and David’s articles still form the essence of the approach. The solution that accompanies this post provides all the necessary .NET based Visual Studio project.  In addition, you’ll need: 1. Jetty 7 runtime http://www.eclipse.org/jetty/downloads.php 2. JRE http://www.oracle.com/technetwork/java/javase/downloads/index.html Once you have these the first step is to create archives (zips) of the distributions.  For this PoC, the structure of the archive requires that the root of the archive looks as follows: JRE6.zip jetty---.zip Upload the contents to a storage container (block blob), and for this example I used /archives as the location.  The service configuration has several settings that allow, which is the advantage of using RoleEntryPoint, the ability to provide these things via native configuration support from Azure in a worker role. Storage Explorer You can use development storage for testing this out – the zipped version of the solution is configured for development storage.  When you’re ready to deploy, you update the two settings – 1 for diagnostics and the other for the storage container where the /archives are going to be stored. <?xml version="1.0" encoding="utf-8"?> <ServiceConfiguration serviceName="HostedJetty" osFamily="2" osVersion="*"> <Role name="JettyWorker"> <Instances count="1" /> <ConfigurationSettings> <!--<Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="DefaultEndpointsProtocol=https;AccountName=<accountName>;AccountKey=<accountKey>" />--> <Setting name="Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString" value="UseDevelopmentStorage=true" /> <Setting name="JettyArchive" value="jetty-distribution-7.3.0.v20110203b.zip" /> <Setting name="StartRole" value="true" /> <Setting name="BlobContainer" value="archives" /> <Setting name="JreArchive" value="jre6.zip" /> <!--<Setting name="StorageCredentials" value="DefaultEndpointsProtocol=https;AccountName=<accountName>;AccountKey=<accountKey>"/>--> <Setting name="StorageCredentials" value="UseDevelopmentStorage=true" />   For interacting with Storage you can use several tools – one tool that I like is from the Windows Azure CAT team located here: http://appfabriccat.com/2011/02/exploring-windows-azure-storage-apis-by-building-a-storage-explorer-application/  and shown in the prior picture At runtime, during role initialization and startup, Azure will call into your RoleEntryPoint.  At that time the code will do a dynamic pull of the 2 archives and extract – using the Sharp Zip Lib <link> as Mario had demonstrated in his sample.  The only different here is the use of CLR code vs. PowerShell (which is really CLR, but that’s another discussion). At this point, once the 2 zips are extracted, the Role’s file system looks as follows: Worker Role approot From there, the OnStart method (which also does the download and unzip using a simple StorageHelper class) kicks off the Java path and now you have Java! Task Manager Jetty Sample Page A couple of things I’m working on to enhance this is to extract the jre and jetty bits not to the appRoot but to a resource location defined as part of the service definition. ServiceDefinition.csdef <?xml version="1.0" encoding="utf-8"?> <ServiceDefinition name="HostedJetty" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"> <WorkerRole name="JettyWorker"> <Imports> <Import moduleName="Diagnostics" /> <Import moduleName="RemoteAccess" /> <Import moduleName="RemoteForwarder" /> </Imports> <Endpoints> <InputEndpoint name="JettyPort" protocol="tcp" port="80" localPort="8080" /> </Endpoints> <LocalResources> <LocalStorage name="Archives" cleanOnRoleRecycle="false" sizeInMB="100" /> </LocalResources>   As the concept matures a bit, being able to update dynamically the content or jar files as part of a running java solution is something that is possible through continued enhancement of this simple model. The Visual Studio 2010 Solution is located here: HostingJavaSln_NDA.zip

    Read the article

  • Android VideoView resume and seekTo

    - by Chris
    I am playing a Video using a VideoView in my app. On the click of a button, it records the current position of the video, and the app opens up the browser with some url. On pressing the back button, the app comes back to video app and resumes the video from where it left off. I looked at the Android Activity lifecycle and saw that onStart() method gets called once the video activity comes to the foreground. So I am creating my layout in onStart() and playing the video by seeking to the current position. My problem is that when the video resumes, it buffers from the start and then seeks to. Since it already buffered the first time, is there a way to eliminate buffering again while doing a seekTo? Thanks Chris

    Read the article

  • HttpWebRequest timeout in Windows service

    - by googler1
    I am getting a timeout error while starting my Windows service. I am tring to download an XML file from a remote system which causes a timeout during the service OnStart. This is the method I am calling from OnStart: public static StreamReader GetResponseStream() { try { EventLog.WriteEntry("Epo-Service_Retriver", "Trying ...", EventLogEntryType.Information); CookieContainer CC = new CookieContainer(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create( Utils.GetWeeklyPublishedURL()); request.Proxy = null; request.UseDefaultCredentials = true; request.KeepAlive = true; //THIS DOES THE TRICK request.ProtocolVersion = HttpVersion.Version10; // THIS DOES THE TRICK request.CookieContainer = CC; WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); EventLog.WriteEntry("Epo-Service_Retriver", "Connected to Internet...", EventLogEntryType.SuccessAudit); return reader; } } Is there any possibility to avoid this timeout?

    Read the article

  • ServiceBus WorkerRole DiagnosticMonitor Error

    - by user1596485
    I have a WebRole and 2 ServiceBus WorkerRoles running, During the OnStart of the roles I get the following Exception: [System.ArgumentOutOfRangeException] invalid syntax for container log4net Parameter name: initialConfiguration Running Azure: ConfigurationManager version=1.7.0.3 ServiceBus version=1.7.0.1 Storage version=1.7.0.0 This occurs while running locally in the dev Azure environment and in the Cloud. All roles have the following Configurtion settings: <LocalStorage name="Log4Net" cleanOnRoleRecycle="true" sizeInMB="2048" /> All Roles have the following code in the OnStart: try { // Configure Disgnostics to poll Log file to Blob Storage var diagnosticsConfig = DiagnosticMonitor.GetDefaultInitialConfiguration(); diagnosticsConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(5); diagnosticsConfig.Directories.DataSources.Add( new DirectoryConfiguration { Path = RoleEnvironment.GetLocalResource("Log4Net").RootPath, DirectoryQuotaInMB = 512, Container = "wad-WebRolelog4net" }); DiagnosticMonitor.Start("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString", diagnosticsConfig); } catch { OnStop(); return false; }

    Read the article

  • VideoView Not Playing, Error(1,-1)

    - by Jesse J
    I originally thought that the video format was wrong, but after trying .mov, .3gp, and .mp4 with H.264, I'm wondering if something is wrong with my code? public class IntroActivity extends Activity { VideoView videoHolder; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onStart() { getWindow().setFormat(PixelFormat.TRANSLUCENT); videoHolder = new VideoView(this); //videoHolder = (VideoView)findViewById(R.id.myvideoview); Uri video = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.menu); videoHolder.setVideoURI(video); videoHolder.start(); videoHolder.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer mp) { videoHolder.start(); } }); setContentView(videoHolder); super.onStart(); }

    Read the article

  • Proper way to 100% wakes my device?

    - by quiel
    Do you have better way to make the device awakes by 100%? I repeatedly call the acquire() but I'm not sure if that is correct. Or should I just call the acquire() once? Or should I make use of Intent.ACTION_SCREEN_OFF? public class MyServiceThatKeepsTheDeviceAwake extends IntentService { ... @Override public void onCreate() { super.onCreate(); mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE, TAG); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); mWakeLock.acquire(); } // No release

    Read the article

  • Solution 6 : Kill a Non-Clustered Process during Two-Node Cluster Failover

    - by StanleyGu
    Using Visual Studio 2008 and C#, I developed a windows service A and deployed it to two nodes of a windows server 2008 failover cluster. The service A is part of the failover cluster service, which means, when failover occurs at node1, the cluster service will failover the windows service A from node 1 to node 2. One of the tasks implemented by the windows service A is to start, monitor or kill a process B. The process B is installed to the two nodes but is not part of the failover cluster service. When a failover occurs at node1, the cluster service does not failover the process B from node 1 to node 2, and the process B continues running at node1. The requirement is: When failover occurs at node1, we want the process B running at node1 gets killed, but we do not want the process B be part of the failover cluster service. The first idea that pops up immediately is to put some code in an event handler triggered by the failover in the windows service A. The failover effect to the windows service A is similar to using the task manager to kill the process of the windows service A, but there is no event in windows service that can be triggered by killing the process of the window service. The events related to terminating a windows service are OnStop and OnShutDown, but killing the process of windows service A triggers neither of them. The OnStop event can only be triggered by stopping the windows service using Services Control Manager or Services Management Console. Apparently, the first idea is not feasible. The second idea that emerges is to put code into the OnStart event handler of the windows service A. When failover occurs at node 1, the windows service A is killed at node 1 and started at node 2. During the starting, the windows service A at node 2 kills the process B that is running at node 1. It is a workaround and works very well. The C# code implementation within the OnStart event handler is as following: 1.       Capture server names of the two nodes from App.config 2.       Determine server name of the remote node. 3.       Kill the process B running on the remote node. Check here for sample code.  

    Read the article

  • Android launches system settings instead of my app

    - by jsundin
    Hi, For some reason whenever I (try to) start my app the phone decides to launch system settings instead of my "main activity". And yes, I am referring to the "Android system settings", and not something from my app. This only happens on my phone, and I suppose it probably could be related to the fact that my app had just opened system settings when I decided to re-launch with a new version from Eclipse. It is possible to start the app from within Eclipse, but when I navigate back from the app it returns to the system settings rather than the home screen, as if the settings activity was started first and then my activity. If I then start the app from the phone all I get is system settings yet again. The app is listening to the VIEW-action for a specific URL substring, and when I start the app using a matching URL I get the same result as when I start it from Eclipse, app starts, but when I return I return to settings. I have tried googling for this problem, and all I could find was something about Android saving state when an app gets killed, but without any information on how to reset this state. I have tried uninstalling the app, killing system settings, rebooting the phone, reinstalling, clearing application data.. no luck.. For what it's worth, here's the definition of my main activity from the manifest, <activity android:name=".HomeActivity" android:label="@string/app_name" android:screenOrientation="portrait" android:clearTaskOnLaunch="true" android:launchMode="singleTop"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW"></action> <category android:name="android.intent.category.DEFAULT"></category> <category android:name="android.intent.category.BROWSABLE"></category> <data android:pathPrefix="/isak-web-mobile/smart/" android:scheme="http" android:host="*"></data> </intent-filter> </activity> And here is the logcat-line from when I try to start my app, nothing about any settings anywhere. I/ActivityManager( 1301): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=se.opencare.isak/.HomeActivity } When I launch from Eclipse I also get this line (as one would expect), I/ActivityManager( 1301): Start proc se.opencare.isak for activity se.opencare.isak/.HomeActivity: pid=23068 uid=10163 gids={3003, 1007, 1015} If it matters the phone is a HTC Desire Z running 2.2.1. Currently, this is my HomeActivity, public class HomeActivity extends Activity { public static final String TAG = "HomeActivity"; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult(" + requestCode + ", " + resultCode + ", " + data + ")"); super.onActivityResult(requestCode, resultCode, data); } @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate(" + savedInstanceState + ")"); super.onCreate(savedInstanceState); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy()"); super.onDestroy(); } @Override protected void onPause() { Log.d(TAG, "onPause()"); super.onPause(); } @Override protected void onPostCreate(Bundle savedInstanceState) { Log.d(TAG, "onPostCreate(" + savedInstanceState + ")"); super.onPostCreate(savedInstanceState); } @Override protected void onPostResume() { Log.d(TAG, "onPostResume()"); super.onPostResume(); } @Override protected void onRestart() { Log.d(TAG, "onRestart()"); super.onRestart(); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { Log.d(TAG, "onRestoreInstanceState(" + savedInstanceState + ")"); super.onRestoreInstanceState(savedInstanceState); } @Override protected void onResume() { Log.d(TAG, "onResume()"); super.onResume(); } @Override protected void onStart() { Log.d(TAG, "onStart()"); super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop()"); super.onStop(); } @Override protected void onUserLeaveHint() { Log.d(TAG, "onUserLeaveHint()"); super.onUserLeaveHint(); } } Nothing (of the above) is written to the log.

    Read the article

  • .NET remoting exception: Exception in the Socket#33711845::DoBind - Only one usage of each socket ad

    - by wollemi
    Hi All, I'm attempting to setup a simple remoting windows service and getting the following error when starting the service: "System.Net.Sockets Error: 0 : [4180] Exception in the Socket#33711845::DoBind - Only one usage of each socket address (protocol/network address/port) is normally permitted System.Net.Sockets Verbose: 0 : [4180] ExclusiveTcpListener#4032828::Start() System.Net.Sockets Verbose: 0 : [4180] Socket#33711845::Bind(0:9998#9998) System.Net.Sockets Error: 0 : [4180] Exception in the Socket#33711845::DoBind - Only one usage of each socket address (protocol/network address/port) is normally permitted ". In the windows service application I have the following code in the "OnStart" method - the error occurs when registering the Channel - ChannelServices.RegisterChannel(tcpPipe, true); As far as I can tell there are no other processes using port 9998 ... Your help to resolve this is most appreciated! protected override void OnStart(string[] args) { int portNumber = int.Parse(ConfigurationManager.AppSettings["endPointTCPPort"]); TcpChannel tcpPipe = new TcpChannel(portNumber); ChannelServices.RegisterChannel(tcpPipe, true); Type serviceType = Type.GetType("TractionGatewayService.TractionGateway"); try { RemotingConfiguration.RegisterWellKnownServiceType(serviceType, "updateCustomerDetails", WellKnownObjectMode.SingleCall); } catch (RemotingException e) { EventLog.WriteEntry("unable to establish listening port because " + e.message; ChannelServices.UnregisterChannel(tcpPipe); } w

    Read the article

  • Android custom media controller using vidtry

    - by Mathias Lin
    I want to use a custom media controller in my Android app and therefore looking at the vidtry code (http://github.com/commonsguy/vidtry), especially Player.java: The sample works fine as it comes. But I want the sample to play the fixed video automatically on app startup (so I don't want to enter a URL). I added: @Override public void onStart() { super.onStart(); address.setText("/sdcard/mydata/category/1/video_agkkr6me.mp4"); go.setEnabled(true); onGo.onClick(go); } Strange thing here is that if I run the app, the audio of the video plays but the image doesn't show. Everything else works fine (progress bar, etc.). I can't figure out the difference between the manual click on the go-button and the programmatic one. I looked at the code and didn't see any difference that might occur between manual and programmatic click. I checked if any elements (esp. surface) might be hidden, but it's not. I even tried a surface.setVisibility(View.INVISIBLE); surface.setVisibility(View.VISIBLE); in case some issue with the redrawing, but no difference. The video image does show when I manually hit the go button, but just not on start up automatically.

    Read the article

  • Upgrade to Azure 2.2 SDK is causing roles to fail

    - by Jon Leach
    I have 3 worker roles and a web role in my project and I upgraded it to the new 2.2 SDK (required in VS2013). Ever since the upgrade, all of the worker roles are failing and they instantly recycle as soon as they're started. When the roles start, I'm getting these messages: Microsoft.WindowsAzure.ServiceRuntime Information: 200 : Role entrypoint . CALLING OnStart() Microsoft.WindowsAzure.ServiceRuntime Information: 202 : Role entrypoint . COMPLETED OnStart() The thread 0x441c has exited with code 259 (0x103). Microsoft.WindowsAzure.ServiceRuntime Information: 203 : Role entrypoint . CALLING Run() Microsoft.WindowsAzure.ServiceRuntime Warning: 204 : Role entrypoint . COMPLETED Run() ==> ROLE RECYCLING INITIATED Microsoft.WindowsAzure.ServiceRuntime Information: 503 : Role instance recycling is starting The thread 0x2684 has exited with code 259 (0x103) Two things draw my attention: I've started to see a bunch of errors "Cannot find or open the PDB file." But I don't know that this is directly relevant. I'm using VS 2013 and while the project lists the SDK as 2.2, the references within the roles are the 2.1 versions. Do I need to upgrade the components? Why wouldn't the project upgrade these automatically when I pulled the project into VS as it only support 2.2? Any thoughts on how to attach this are appreciated.

    Read the article

  • android bindservice

    - by mnish
    hi, I get null pointer exception at line mService.start() when i try to bind to an already started service. I do the same thing from different activity(where the service gets started) everythig goes right. All these activities are part of one application. What do you think I do wrong? public class RouteOnMap extends MapActivity{ private static final int NEW_LOCATION = 1; private static final int GPS_OFF = 2; private MapView mMapView; private ILocService mService; private boolean mServiceStarted; private boolean mBound; private Intent mServiceIntent; private double mLatitude, mLongitude; private ServiceConnection connection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder iservice) { mService = ILocService.Stub.asInterface(iservice); mBound = true; } public void onServiceDisconnected(ComponentName className) { mService = null; mBound = false; } }; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.mapview); mMapView = (MapView) findViewById(R.id.mapview); mMapView.setBuiltInZoomControls(true); mServiceIntent = new Intent(); mLatitude = 0.0; mLongitude = 0.0; mBound = false; } @Override public void onStart(){ super.onStart(); mServiceIntent.setClass(this, LocationService.class); //startService(mServiceIntent); if(!mBound){ mBound = true; this.bindService(mServiceIntent, connection, Context.BIND_AUTO_CREATE); } } @Override public void onResume(){ super.onResume(); try { mService.start(); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onPause(){ super.onPause(); if(mBound){ this.unbindService(connection); } } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } }

    Read the article

  • Windows Service Conundrum

    - by Paul Johnson
    All, I have a Custom object which I have written using VB.NET (.net 2.0). The object instantiates its own threading.timer object and carries out a number of background process including periodic interrogation of an oracle database and delivery of emails via smtp according to data detected in the database. The following is the code implemented in the windows service class Public Class IncidentManagerService 'Fakes Private _fakeRepoFactory As IRepoFactory Private _incidentRepo As FakeIncidentRepo Private _incidentDefinitionRepo As FakeIncidentDefinitionRepo Private _incManager As IncidentManager.Session 'Real Private _started As Boolean = False Private _repoFactory As New NHibernateRepoFactory Private _psalertsEventRepo As IPsalertsEventRepo = _repoFactory.GetPsalertsEventRepo() Protected Overrides Sub OnStart(ByVal args() As String) ' Add code here to start your service. This method should set things ' in motion so your service can do its work. If Not _started Then Startup() _started = True End If End Sub Protected Overrides Sub OnStop() 'Tear down class variables in order to ensure the service stops cleanly _incManager.Dispose() _incidentDefinitionRepo = Nothing _incidentRepo = Nothing _fakeRepoFactory = Nothing _repoFactory = Nothing End Sub Private Sub Startup() Dim incidents As IList(Of Incident) = Nothing Dim incidentFactory As New IncidentFactory incidents = IncidentFactory.GetTwoFakeIncidents _repoFactory = New NHibernateRepoFactory _fakeRepoFactory = New FakeRepoFactory(incidents) _incidentRepo = _fakeRepoFactory.GetIncidentRepo _incidentDefinitionRepo = _fakeRepoFactory.GetIncidentDefinitionRepo 'Start an incident manager session _incManager = New IncidentManager.Session(_incidentRepo, _incidentDefinitionRepo, _psalertsEventRepo) _incManager.Start() End Sub End Class After a little bit of experimentation I arrived at the above code in the OnStart method. All functionality passed testing when deployed from VS2005 on my development PC, however when deployed on a true target machine, the service would not start and responds with the following message: "The service on local computer started and then stopped..." Am I going about this the correct way? If not how can I best implement my incident manager within the confines of the Windows Service class. It seems pointless to implement a timer for the incidentmanager because this already implements its own timer... Any assistance much appreciated. Kind Regards Paul J.

    Read the article

  • Changing text of TextView -- old text doesn't go away (Android 4.1.2)

    - by Jason Costabile
    I'm pretty new to Android development. Trying to accomplish something fairly simple -- change some displayed text when a timer ticks. Here's the potentially relevant code: CountDownTimer currentTimer; Resources res; TextView timerText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_exercise); res = getResources(); timerText = (TextView) findViewById(R.id.timer_text); } @Override protected void onStart() { super.onStart(); //"Get ready" countdown currentTimer = new CountDownTimer(5000, 1000) { @Override public void onTick(long millisUntilFinished) { timerText.setText("" + (int)Math.ceil(millisUntilFinished / 1000.0)); } @Override public void onFinish() { ... } }; currentTimer.start(); } This works fine on an emulated 4.2.2 device, but on a 4.1.2 device (both physical and emulated), the changed TextView appears as such while the countdown proceeds: If you can't tell, that's the numbers 5,4,3 overlayed. So, when I set a new string for the TextView, the new string is displayed but without replacing the old string. Any other TextViews used in my app behave in the same way. Any ideas what the problem is and how to fix it? Edit: From the XML layout file: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".ExerciseActivity" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:keepScreenOn="true" android:orientation="vertical" > ... <TextView android:id="@+id/timer_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:textIsSelectable="false" android:hint="@string/timer_default" /> ... </LinearLayout> That's all that could be relevant.

    Read the article

  • Problems with Acitivity LifeCycle with VideoView playback.

    - by Alex Volovoy
    Hi all i've ran into another problems with VideoView. Then video is playing, and i put device asleep, using hard button, onPause is called. But it followed by 03-17 11:26:33.779: WARN/ActivityManager(884): Activity pause timeout for HistoryRecord{4359f620 com.package/com.package.VideoViewActivity} And then i have onStart/onResume again and Video starts playing. I've try to move code around onStart/onStop - doesn't seems to make difference. sample code : public class VideoViewActivity extends Activity { private String path = ""; private VideoView mVideoView; private static final String MEDIA_URL = "media_url"; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.videoview); mVideoView = (VideoView)findViewById(R.id.surface_view); path = getIntent().getStringExtra(MEDIA_URL); } @Override public void onResume() { super.onResume(); mVideoView.setVideoPath(path); mVideoView.setMediaController(new MediaController(this)); mVideoView.requestFocus(); mVideoView.start(); } @Override public void onPause() { super.onPause(); mVideoView.stopPlayback(); mVideoView.setMediaController(null); } }

    Read the article

  • Send a public broadcast from an AppWidget in Android

    - by greve
    I have a widget for a music player and want to be able to send broadcasts when pushing the different buttons. What I want to do is when a button is pushed, the widget sends a public broadcast to another BroadcastReceiver so it can handle the different actions. In my activity class with the BroadcastReceiver: private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Constants.ACTION_NEXT)) { Log.d("RECEIVER", "ACTION_NEXT"); } } }; @Override protected void onStart() { super.onStart(); IntentFilter filter = new IntentFilter(); //Widget actions filter.addAction(Constants.ACTION_NEXT); registerReceiver(broadcastReceiver, new IntentFilter(filter)); } In my Widget: public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(Constants.ACTION_NEXT), 0); views.setOnClickPendingIntent(R.id.WidgetNextButton, pendingIntent); appWidgetManager.updateAppWidget(appWidgetId, views); } Any help or other solutions are very much appreciated!

    Read the article

  • Problems with WCF endpoints hosted from Windows Service

    - by Dilip
    I have a managed Windows Service that hosts a couple of WCF endpoints. The service is set to start automatically when the PC is restarted. On reboot I find that this line of code: ServiceHost wcfHost1 = new ServiceHost(typeof(WCFHost1)); in the OnStart() method of the service takes somewhere between 15 - 20 seconds to execute. Actually I have two such statements but the second one executes in a flash. It is the first one that takes so long. Does anyone know what could be causing the bottleneck? Because of this, sometimes the call exceeds 30 seconds and as a result the SCM thinks my service timed out while trying to initialize itself. Now, I know its easy for me to just spin off a thread to do this and return from OnStart() right away but I'd like to know what could cause this delay. This happens only when the service starts up on PC reboot. If the PC is up and running, the service starts & stops in less than a second.

    Read the article

  • Why does GetWindowThreadProcessId return 0 when called from a service

    - by Marve
    When using the following class in a console application, and having at least one instance of Notepad running, GetWindowThreadProcessId correctly returns a non-zero thread id. However, if the same code is included in a Windows Service, GetWindowThreadProcessId always returns 0 and no exceptions are thrown. Changing the user the service launches under to be the same as the one running the console application didn't alter the result. What causes GetWindowThreadProcessId to return 0 even if it is provided with a valid hwnd? And why does it function differently in the console application and the service? Note: I am running Windows 7 32-bit and targeting .NET 3.5. public class TestClass { [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId); public void AttachToNotepad() { var processesToAttachTo = Process.GetProcessesByName("Notepad") foreach (var process in processesToAttachTo) { var threadID = GetWindowThreadProcessId(process.MainWindowHandle, IntPtr.Zero); .... } } } Console Code: class Program { static void Main(string[] args) { var testClass = new TestClass(); testClass.AttachToNotepad(); } } Service Code: public class TestService : ServiceBase { private TestClass testClass = new TestClass(); static void Main() { ServiceBase.Run(new TestService()); } protected override void OnStart(string[] args) { testClass.AttachToNotepad(); base.OnStart(args); } protected override void OnStop() { ... } }

    Read the article

  • Why doesn't my text be bold when displaying on device screen

    - by john123
    My string.xml: <!--I try to bold my argument %s, like below:--> <string name="hello">Hello to: <b>%s</b> !</string> My layout main.xml: <LinearLayout ...> <TextView android:id="@+id/hello_txt" ... .../> </LinearLayout> My Fragment class: public class MyFragment extends Fragment{ TextView helloTxt; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); helloTxt = (TextView) findViewById(R.id.hello_txt); } @Override public void onStart() { super.onStart(); //pass "Monday" as the argument to my string helloTxt.setText(String.format(getString(R.string.hello), "Monday")); } } When I run my app on my device, I got "Hello to: Monday !" displaying on screen, but the "Monday" is not bold, but I used <b> in my string.xml. Why it is not bold??

    Read the article

  • Google Analytics version 3 - How to apply it correctly?

    - by ephramd
    I've added google analytics to my app with the intention of obtaining information about the screens you and send custom events. I am obtained duplicate content ... Also I get different results: "com.package.app.MainScreen" - 300 views and "Main Screen" - 200 views I am interested to get only follow up with the custom name of the activity and not the package. And in any case, because both show different results? public class MainScreen extends Activity { private static final String GA_PROPERTY_ID = "UA-12345678-9"; private static final String SCREEN_LABEL = "Main Screen"; Tracker mTracker; EasyTracker easyTracker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_screen); mTracker = GoogleAnalytics.getInstance(this).getTracker(GA_PROPERTY_ID); mTracker.set(Fields.SCREEN_NAME, SCREEN_LABEL); // For Custom Name from activity mTracker.send(MapBuilder.createAppView().build()); easyTracker = EasyTracker.getInstance(this); // Analytics Events ... easyTracker.send(MapBuilder.createEvent("MainScreen", "Play", category.get(1), null).build()); //AnalyticsEvents ... } @Override public void onStart() { super.onStart(); EasyTracker.getInstance(this).activityStart(this); } @Override public void onStop() { super.onStop(); EasyTracker.getInstance(this).activityStop(this); } } And analytics.xml: <?xml version="1.0" encoding="utf-8" ?> <resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="TypographyDashes"> <!--Replace placeholder ID with your tracking ID--> <string name="ga_trackingId">UA-12345678-9</string> <!--Enable automatic activity tracking--> <bool name="ga_autoActivityTracking">true</bool> <!--Enable automatic exception tracking--> <bool name="ga_reportUncaughtExceptions">true</bool> </resources> Google Analytics Dev Guide

    Read the article

  • Windows Forms application C# | Sending Tweet

    - by Andrew Craswell
    I've been able to get my Twitter web app working just fine, but I've recently decided to add Tweeting functionality from a Windows Form, but I'm having no luck sending tweets. No errors are thrown or anything. Mind looking over my code? using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using TweetSharp; namespace TwitterAdvirtiser { public partial class Form1 : Form { private string cKey = "xxx"; private string cSecret = "xxx"; private string oToken = "xxx"; private string aToken = "xxx"; public Form1() { InitializeComponent(); OnStart(); } private void OnStart() { //Authenticate with Twitter TwitterService service = new TwitterService(cKey, cSecret); service.AuthenticateWith(oToken, aToken); service.SendTweet("testing"); } } } It seems like I'm authenticating just fine, I can walk through debug mode and see all my details in the TwitterUser structure, and yet my tweets never show up on my feed. Whats up? By the way, I'm using Visual Studios 2010, and .NET 4.0. I have verified that the oToken and aToken strings have my developer tokens.

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >