My AlarmManager for service update doesn't work - android

Why my AlarmManager for service update doesn't work? this is my code:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService();
}
// Method to start the service
public void startService() {
startService(new Intent(getBaseContext(), MyService.class));
}
// Method to stop the service
public void stopService() {
stopService(new Intent(getBaseContext(), MyService.class));
}
Service class:
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onCreate() {
poruka();
super.onCreate();
}
public void poruka(){
Toast.makeText(this, "OnCreate work!", Toast.LENGTH_LONG).show();
}
}
BroadcastReceiver and AlarmManager:
public class ServiceBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MyService.class));
Intent alarmIntent = new Intent(context, ServiceBroadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis(), 30*1000, pendingIntent);
}
}
And Permissions:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="me.example.nservice.MainActivity"
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=".MyService" android:enabled="true"
android:label="Servisv1" />
<receiver android:name="me.example.rqservice.ServiceBroadcast" android:process=":remote">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
I receive message "OnCreate work!" and "Service Started" only first time when i open app. Why update doesn't work every 30 sec?

To start a service every 30 seconds :
Inside onCreate() :
Here MyService is the name of the Service.
Intent myService = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(
this, 0, myService, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 30*1000,pendingIntent);
This'll start your service every 30 seconds. However, if the service is already running, which might be the case once it has been started the first time, from next time onwards the call will directly go to onStartCommand() method of the Service and not onCreate().
This is all that you need to do. However, if you want to make sure that the AlarmManager keeps restarting the service even after a phone is restarted, you'll need to add a BroadcastReceiver for Boot.

Related

AlarmManager Pending intent not working with broadcast receiver

I am working on an App in which i want to set custom alarm.but after setting a time on alarm nothing happens. i am sharing my code. Please help and guide me if something is missing in my code.
In my MainActivity.java
#Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_ID) {
return new TimePickerDialog(MainActivity.this, kTimePickerListener, hour, min, false);
}
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hourofday, int minutes) {
hour = hourofday;
min = minutes;
Calendar calendar = Calendar.getInstance();
// set selected time from timepicker to calendar
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minutes);
Intent myIntent = new Intent(MainActivity.this, ServiceManager.class);
myIntent.putExtra("reqcode", 11);
// A PendingIntent specifies an action to take in the
// future
PendingIntent mPendingIntent = PendingIntent.getBroadcast(MainActivity.this, 11, myIntent, 0);
// set alarm time
alarmManager = (AlarmManager) MainActivity.this
.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), mPendingIntent);
}
};
In My ServiceManager.class
public class ServiceManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int Noti_code = intent.getIntExtra("reqcode",-1);
Intent myIntent = new Intent(context, NotificationService.class);
myIntent.putExtra("reqcode", Noti_code);
context.startService(myIntent);
}
}
In My NotificationService.class
public class NotificationService extends Service {
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#SuppressWarnings({"static-access", "deprecation"})
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
int Noti_Code = intent.getIntExtra("reqcode",-2);
if (Noti_Code == 11) {
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
ShowNotification(getApplicationContext(), mManager);
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
In my Manifest.xml
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activity_detail" />
<activity android:name=".History" />
<service
android:name=".NotificationService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false"/>
<receiver android:name=".ServiceManager"
android:process=":remote"/>
</application>
I am checking through debugging broadcast receiver doesn't called. Please help me if i am missing any thing.
Also i want to know how many pending intent can be fire at a time and will all works one by one?
Thanks.
Refrence links:
AlarmManager wont fire pending intent
http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/
BroadcastReceiver and AlarmManager not working with
AlarmManager is not working after app is closed? - Android
You have your BroadcastReceiver running in another process. If you are setting breakpoints with a debugger you will miss this. If you don't need your BroadcastReceiver running in a separate process, remove the
android:process=":remote"
declaration from the manifest.
See the documentation about how the android:process specifier works.

Repeating alarm is not working in marshmallow

I am using the following code to start a service periodically whether the app is foreground or not .
Intent getAlertIntent = new Intent(getApplicationContext(), GetAlertAlarmReceiver.class);
PendingIntent getAlertpendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, getAlertIntent, 0);
AlarmManager getAlertmanager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
getAlertmanager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, getAlertpendingIntent);
The code for my receiver is following
public class GetAlertAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, GetAlertServiceIntent.class);
context.startService(i);
}
}
And and service
public class GetAlertServiceIntent extends IntentService {
public GetAlertServiceIntent() {
super("GetAlertServiceIntent");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
protected void onHandleIntent(Intent intent) {
doSomething();
}
}
In my manifest file I declared everything as following
<receiver
android:name=".broadcastreceiver.GetAlertAlarmReceiver"
android:enabled="true">
<intent-filter android:priority="999">
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name="com.surroundapps.shotorkoporibar.services.GetAlertServiceIntent" />
This code work as expected in API level below Marshmallow but in marshmallow it doesn't work .

Why is my alarm not being executed?

I have an Activity that is supposed to launch a Service via a BroadcastReceiver.
Overview of the three:
Activity = Tracking
Service = PhoneManagementService
BroadcastReceiver = TrackingRestart
The Activity launches the AlarmManager in the onCreate() method:
public class Tracking extends Activity {
private static final int ALARM_FREQUENCY_SECONDS = 60;
#Override
protected void onCreate(Bundle savedInstanceState) {
startService(new Intent(Tracking.this, PhoneManagementService.class));
Intent alarm = new Intent(this, TrackingRestart.class);
boolean alarmRunning = (PendingIntent.getBroadcast(this, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
if(!alarmRunning) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), (ALARM_FREQUENCY_SECONDS * 1000), pendingIntent);
}
}
I included startService(new Intent(Tracking.this, PhoneManagementService.class)); in there because this is the only time that the Service is called.
The BroadcastReceiver looks like this:
public class TrackingRestart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, PhoneManagementService.class));
context.stopService(new Intent(context, PhoneManagementService.class));
}
}
The Service class looks like this:
public class PhoneManagementService extends Service {
private String user = "Service";
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
startForeground(NotificationCreator.getNotificationId(), NotificationCreator.getNotification(this));
DBAdapter newEntry = new DBAdapter(this);
newEntry.open();
newEntry.addEntry("charging", user, getChargerType());
newEntry.addEntry("battery", user, getBatteryStats());
newEntry.addEntry("network", user, getNetworkType());
newEntry.close();
}
}
The Manifest containts those three entries:
<activity android:name=".Tracking">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".GPSService"
android:process=":trackingService_gps"
android:launchMode="singleTop"
android:enabled="true" />
<service
android:name=".PhoneManagementService"
android:process=":trackingService_phoneManagement"
android:launchMode="singleTop"
android:enabled="true" />
<receiver
android:name=".TrackingRestart"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="ch.jpabig.jonastrackingapp.ActivityRecognition.RestartTracking"/>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
<action android:name="android.intent.action.BATTERY_LOW"/>
<action android:name="android.intent.action.BATTERY_OKAY"/>
</intent-filter>
</receiver>
Somehow the entries into the database are not made and I'm at a lost why this is the case. It must be the alarm but I could be very wrong.

How to start service after reboot device in Android

I want start my Service after reboot device, I write below codes but when reboot device not start Service.
Manifest:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".alarm1.alarm1"></activity>
<receiver android:name=".alarm1.AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<!-- Will not be called unless the application explicitly enables it -->
<receiver android:name=".alarm1.DeviceBootReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Activity code:
public class alarm1 extends AppCompatActivity {
private PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm1);
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);
findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
start();
}
});
findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancel();
}
});
findViewById(R.id.stopAlarmAt10).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAt10();
}
});
}
public void start() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 8000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
public void cancel() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
public void startAt10() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 1000 * 60 * 20;
/* Set the alarm to start at 10:30 AM */
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 15);
Toast.makeText(alarm1.this, "Start at 17:11", Toast.LENGTH_SHORT).show();
/* Repeating on every 20 minutes interval */
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 3, pendingIntent);
}
}
AlarmReceiver codes:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
}
DeviceBootReceiver codes:
public class DeviceBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
/* Setting the alarm here */
Intent alarmIntent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
int interval = 8000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(context, "Alarm Set", Toast.LENGTH_SHORT).show();
}
}
}
How can I fix this and when reboot device start Service?
Add permissions in Manifest.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Add receiver entry in Manifest.
<receiver android:enabled="true" android:name=".alarm1.DeviceBootReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
You just need to
Request a permission
and
Explicitly enable the receiver.
The permission goes in the manifest file:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Then when the user sets an alarm (for example your start method), enable the boot receiver:
ComponentName receiver = new ComponentName(context, DeviceBootReceiver.class);
getPackageManager().setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
When the user cancels all alarms, you should disable the boot receiver using a similar piece of code.

receiver and service

With the courtesy of an stackoverlow user we written this code. Should be starts a toast at specify hour but doesn't run.
Can someone help me to discover where's the problem?
thanks!
public class UnUsedService extends Service {
private PendingIntent pendingIntent;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
//startService(new Intent(this, UnUsedService.class));
}
#Override
public void onDestroy() {
super.onDestroy();
//Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// super.onStart();
super.onStart(intent, startId);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
//Toast.makeText(UnUsedService.this, "Start Alarm", Toast.LENGTH_LONG).show();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 22);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0); AlarmManager am = (AlarmManager) getApplicationContext().getSystemService (Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(getApplicationContext(), 0, new Intent(getApplicationContext(), AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
}};
The receiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
}
Manifest:
<service android:name="UnUsedService">
<intent-filter>
<action
android:name="org.gortcloud.startatboot.UnUsedService" />
</intent-filter>
</service>
<receiver android:name=".AlarmReceiver" android:process=":remote"/>
I was just working on something similar. can you replace receiver android:name=".AlarmReceiver" with receiver android:name=".AlarmReceiver" android:process=":remote" that worked for me.
ok...i got this to work. i followed How to start Service using Alarm Manager in Android?. basically i was using a pendingIntent.setBroadcast(..) which requires a BroadcastReceiver, now i'm using pendingIntent.setService(...)
i have a class that extends IntentService (with a noarg constructor). I'm successfully getting the alarm to trigger starting this service. i have an onStart() and onStartCommand() and onHandleIntent() that each get run (i assume you would only implement one of them)
hope this helps you.

Categories

Resources