Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntentService won't start using AlarmManager

I know there is a lot of questions about this but I really don't know where is my mistake.

My service is registered in the AndroidManifest.xml file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.app" >
        ...
        <service android:name="com.example.android.app.ScheduledService">
        </service>
    </application>
</manifest>

My service extends IntentService

public class ScheduledService extends IntentService {
    public ScheduledService() {
        super("ScheduledService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(getClass().getSimpleName(), "I ran!");
    }
}

My Activity starts the service

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.d(getClass().getSimpleName(), "Setting alarm!!");

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent alarmIntent = new Intent(this, com.example.android.app.ScheduledService.class);
        PendingIntent pending = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() +
                        10 * 1000, pending);
    }
}

I don't see any exception in the logs. Is there something else I should do to setup my alarm?

like image 597
Migore Avatar asked Mar 14 '14 01:03

Migore


People also ask

How do I start IntentService?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view, when user gets the data from intent service it will update.

Why IntentService is deprecated?

This class was deprecated in API level 30. IntentService is subject to all the background execution limits imposed with Android 8.0 (API level 26). Consider using WorkManager or JobIntentService , which uses jobs instead of services when running on Android 8.0 or higher.

Does IntentService run on background thread?

IntentService runs on its own thread. It will stop itself when it's done.

How do I get context in IntentService?

You can get the context in onStartCommand() function. Show activity on this post. Show activity on this post. You can use Intent service class as Context.


1 Answers

The API says:

typically comes from IntentSender.getBroadcast().

that means PendingIntent.getService can work too. I tested it, and it works.

like image 71
linjo wanbo Avatar answered Oct 19 '22 04:10

linjo wanbo