Issue
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
You should use getService
instead of getActivity
and pass the application context (getApplicationContext
) instead of activity context (this
).
//Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(getApplicationContext(), RingAlarm.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 12345, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 3000, pendingIntent);
RingAlaram.class
public class RingAlarm extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "hi there", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Also set flag to PendingIntent.FLAG_UPDATE_CURRENT instead of CANCEL
And set service declaration on manifest to <packagename>.RingAlarm
might be com.example.alarmmanagerexample.RingAlarm
in your case (I don't know your project structure).
Answered By - AC-OpenSource
Answer Checked By - Clifford M. (JavaFixing Volunteer)