简体   繁体   中英

Android : Starting a Service from an Intent service

I have got the Activity Recognition Intent Service form the Location API running in my app. I would like to start a service when the user activity changes. But I cant seem to get it work. Here is what I have tried:

In the Intent Service class for the activity recognition intent service: (Edit: Added a log to the if condition.)

 @Override
 protected void onHandleIntent(Intent intent) 
 {
        // Get the update
        ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);

        // Get the most probable activity from the list of activities in the update
        DetectedActivity mostProbableActivity = result.getMostProbableActivity();

        // Get the type of activity
        int currentActivity = mostProbableActivity.getType();      

        if(currentActivity == DetectedActivity.IN_VEHICLE)
        {
            Log.w("Rakshak", "in the if condition"); <-- this gets posted.
            sendNotification(); // this just send a notification that the service has started. 
            Intent i = new Intent(this, MyService.class);
            intent.setAction("start");
            startService(i);   <-- this dose'nt start the service. 

        }
}

In the Manifest:

 <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />

 <application
     ....

     <service android:name="driver.rakshak.drivetrackeradmin.MyService"/>    

    <service android:name="driver.rakshak.drivetrackeradmin.ActivityRecognitionIntentService"/>  
 </application>

I have got a button that the user can click to manually start the service and that works fine. It is only here when I would like the service to start automatically it doesn't work.

The app doesn't crash so I don't have any errors form the log to post.

Let me know if you need to see any more of the code.

Cheers.

Since the Context of the IntentService is destroyed after onHandleIntent returns, the Intent created by

Intent i = new Intent(this, MyService.class);

isn't valid anymore.

Try creating your Intent via getApplicationContext()

Intent i = new Intent(getApplicationContext(), MyService.class);

This might solve this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM