'android alarm manager run background service every 15 minute
hey there i am trying to run android background service every 15 minutes using alarm manager but i am unable to do so i don't what mistake and i can't figure out whats wrong in my code its not working
try {
//Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(this, RingAlarm.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
3000,pendingIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
RingAlaram.class
public class RingAlarm extends Service {
public void onCreate() {
Toast.makeText(getApplicationContext(), "hi there", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
and last my manifest
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.alarmmanagerexample.AlarmManagerExample"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".RingAlarm"
android:exported="false" />
</application>
Solution 1:[1]
Change getActivity to getService
Intent intent = new Intent(this, RingAlarm.class);
PendingIntent pendingIntent = PendingIntent.getService(this,
12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
3000,pendingIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ankita Bansal |