Android service not working when app is closed - java

I'm having trouble with an android service that I'm doing. The service is about to get the location of the user every 5 minutes. All seems to go well except when i kill the app, the service won't do nothing. In the code you will ses its checking every 60 seconds I think, but this will change to 5 minutes.
Minimum Target Version: API 23
Target Version: API 29
Android Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.venomapps.meets">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application
android:name=".Utils.App"
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=".Activities.RegisterActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Activities.MainActivity" />
<activity android:name=".Activities.LoginActivity">
</activity>
<service android:name=".Services.LocationService"
android:enabled="true"
android:exported="true"/>
</application>
Code that executes the service:
AlarmManager am=(AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), LocationService.class); intent.setAction(Constants.ACTION_START_LOCATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), Constants.LOCATION_SERVICE_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 60000, pendingIntent);
Service:
public class LocationService extends Service {
private LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult != null && locationResult.getLastLocation() != null) {
double latitude = locationResult.getLastLocation().getLatitude();
double longitude = locationResult.getLastLocation().getLongitude();
Log.d("LOCATION_UPDATE", latitude + ", " + longitude);
stopLocationService();
}
}
};
#Nullable
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
public void startLocationService() {
String channelId = "location_notification_channel";
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent resultIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
getApplicationContext(),
channelId
);
builder.setSmallIcon(R.drawable.ic_app);
builder.setContentTitle("Location Service");
builder.setDefaults(NotificationCompat.DEFAULT_ALL);
builder.setContentText("Running");
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(false);
builder.setPriority(NotificationCompat.PRIORITY_MAX);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (notificationManager != null && notificationManager.getNotificationChannel(channelId) == null) {
NotificationChannel notificationChannel = new NotificationChannel(
channelId, "Location Service", NotificationManager.IMPORTANCE_HIGH
);
notificationChannel.setDescription("This channel is used by location service");
notificationManager.createNotificationChannel(notificationChannel);
}
}
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(8000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.getFusedLocationProviderClient(this)
.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
startForeground(Constants.LOCATION_SERVICE_ID, builder.build());
}
private void stopLocationService(){
LocationServices.getFusedLocationProviderClient(this)
.removeLocationUpdates(locationCallback);
stopForeground(true);
stopSelf();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null){
String action = intent.getAction();
if(action != null){
if(action.equals(Constants.ACTION_START_LOCATION_SERVICE)){
startLocationService();
}
}
}
return super.onStartCommand(intent, flags, startId);
}
}

AlarmManager is deprecated if used for that purpose. Have a look at WorkManager.

Related

Notification Builder action not working on API 31 (Android 12)

I'm stuck while dealing with this api 31. i made a chat app. When I create an action button to receive a phone call it works on android below API 31 or below Android 12, but it doesn't work on Android 12 (only work if the notification is not has action). maybe someone here can help me in finding a solution to this problem?
FirebaseService.java
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
boolean cancelNotification = false;
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Map<String, String> params = remoteMessage.getData();
JSONObject data = new JSONObject(params);
PendingIntent pendingIntent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE);
}
else {
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
}
String channel_id = getNotificationData(data, "channel");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channel_id)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getNotificationData(data, "title"))
.setContentText(getNotificationData(data, "body"))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
if(channel_id.equals("cll2") && getNotificationData(data, "call_action").equals("open")){
playCallSound(this);
if(WindowUtil.isAppOnBackground(this) || isScreenOff()){
ArrayList<String> par = new ArrayList<>();
par.add("call_channel");
par.add("call_type");
par.add("call_token");
par.add("call_peer");
String callType = getNotificationData(data, "call_type");
if(callType.equals("3") || callType.equals("4")){
par.add("call_group_name");
par.add("call_group_caller");
}
Intent receiveCallAction = new Intent(this, CallReceiver.class);
receiveCallAction.putExtra("action", "ANSWER");
Intent cancelCallAction = new Intent(this, CallReceiver.class);
cancelCallAction.putExtra("action", "DECLINE");
for (String s : par) {
receiveCallAction.putExtra(s, getNotificationData(data, s));
cancelCallAction.putExtra(s, getNotificationData(data, s));
}
notificationBuilder.setOngoing(true);
receiveCallAction.setAction("RECEIVE_CALL");
cancelCallAction.setAction("CANCEL_CALL");
PendingIntent receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder
.addAction(R.drawable.ic_baseline_call_24_green, "Answer", receiveCallPendingIntent)
.addAction(R.drawable.ic_baseline_call_red_24, "Decline", cancelCallPendingIntent);
}else{
cancelNotification = true;
}
}if(channel_id.equals("cll2") && getNotificationData(data, "call_action").equals("end_timeout")){
stopRinging();
}else if(channel_id.equals("ntf1")){
if(UserUtil.IS_CHAT_ACTIVITY){
cancelNotification = true;
}
if(!cancelNotification){
playNotificationSound(this);
}
}
if(!cancelNotification){
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
NotificationChannel channel = new NotificationChannel(channel_id,
getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH);
channel.enableLights(true);
channel.enableVibration(true);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(1000, notificationBuilder.build());
}
}
CallReceiver.java (Broadcast Receiver)
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getExtras() != null) {
String action = intent.getStringExtra("action");
// Perform the action
performClickAction(context, action, intent.getExtras());
// Close the notification after the click action is performed.
NotificationManager mNotificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(1000);
// Stop the ringtone
stopRinging();
}
}
on my AndroidManifest.xml
<service
android:name=".services.FirebaseService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<receiver
android:name=".receiver.CallReceiver"
android:exported="false"
android:enabled="true">
<intent-filter>
<action android:name="CALL_RECEIVER" />
</intent-filter>
</receiver>
Thank you
i solve this problem by this code
PendingIntent receiveCallPendingIntent;
PendingIntent cancelCallPendingIntent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
}else{
receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
}
also add this permission for force Android 12^ (AndroidManifest.xml)
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /><receiver
android:name=".receiver.CallReceiver"
android:exported="false"
android:enabled="true"
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>

ANDROID STUDIO- Service not working when device disconnected to power

I have a problem and that is that the service I use in an Android project does not work when I disconnect the device from the power. If it is connected, it does work. I have tried many alternatives and the last thing I tried is this.
I need help... anything that can solve this problem?
Android Manifest and Service
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.resolucion.probando" >
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<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/Theme.Probando" >
<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=".SegundaActivity"></activity>
<service android:process=":remote" android:name=".NuevoIntento"></service>
</application>
</manifest>
public class NuevoIntento extends Service {
private ScheduledExecutorService scheduleTaskExecutor;
private Context context;
TextView tv;
int hora;
int minutos;
int seconds;
int minutosumado;
#Override
public IBinder onBind(Intent intent) {
Log.e("TAG", "Service binding");
return null;
}
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
setNotification();
if (scheduleTaskExecutor == null) {
scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
scheduleTaskExecutor.scheduleAtFixedRate(new mainTask(), 0, 10, TimeUnit.SECONDS);
}
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_main, null);
tv = layout.findViewById(R.id.hora);
return Service.START_STICKY;
}
public void setNotification() {
PendingIntent contentIntent;
contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle("MainActivity")
.setSmallIcon(R.drawable.ic_launcher_background)
.setColor(this.getResources().getColor(R.color.black))
.setOngoing(true)
.setAutoCancel(false)
.setContentText("MyApp");
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(101, mBuilder.build());
Notification notification = mBuilder.build();
startMyOwnForeground(); //NOTIFICATION_ID is a random integer value which has to be unique in an app
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
private class mainTask implements Runnable {
public void run() {
Log.e("TAG","TAG");
}
}
}

AlarmManager doesn't work when app is force closed

It's supposed to be a simple to do list app. You can set a list Item with a task and time. It should send you a notification at the given time.
Everything works fine when the app is running but when I close it I don't get notifications. I tried on API 23 and API R. I was looking at other posts but I couldn't find any solution.
Receiver class:
public class AlertReceiver extends BroadcastReceiver {
NotificationManagerCompat notificationManager;
#Override
public void onReceive(Context context, Intent intent) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
boolean is24HourFormat = android.text.format.DateFormat.is24HourFormat(context);
CharSequence setTime;
if (is24HourFormat) {
setTime = DateFormat.format("HH:mm", calendar);
} else {
setTime = DateFormat.format("hh:mm a", calendar);
}
String currentTime = setTime.toString();
DataBaseHelper dataBaseHelper = new DataBaseHelper(context);
Item itemForNotificationText = dataBaseHelper.GetNotificationContent(currentTime);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
Notification notification = new NotificationCompat.Builder(context,CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
.setContentTitle(itemForNotificationText.getTask())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentText(itemForNotificationText.getTime())
.build();
notificationManager.notify(dataBaseHelper.GetID(),notification);
}
}
I tired using setExactAndAllowWhileIdle but still doesn't work.
Start alarm:
public void startAlarm (Calendar c){
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, item.getNotification_id(), intent,0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
}
}
Manifest file:
<application
android:name=".App"
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=".InsertActivity"></activity>
<activity
android:name=".ToDoList"
android:parentActivityName=".MainActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlertReceiver"/>
</application>
APP Class(Notification channel is created here):
public class App extends Application {
public static final String CHANNEL_1_ID = "Channel 1";
#Override
public void onCreate() {
super.onCreate();
CreateNotificationChannels();
}
private void CreateNotificationChannels () {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("Notifies you when an event has started.");
channel1.enableVibration(true);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
}
}
}

Start ForegroundService on Boot api 29

I try to start a ForegroundService by an BroadcastReceiver on Boot. I have tried this on a device with Android 8 and on an emulated Android 10 device. Both work fine. The problem is, that this code does not work on my Android 10 Galaxy S9. I have debugged everything, my BroadcastReceiver and the OnStartCommand method but also if the BroadcastReceiver runs the code fine, the OnStartCommand method does not start running.
I have a mainActivity in which the user has to apply this Process so the app gets opened once before the BroadcastReceiver should work.
I tried almost every solution i found here but nothing worked for me.
I don't understand why this is working on some devices but not on each. I hope someone can help me!
My min API is 26.
BroadcastReceiver
public class Restarter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent intentt = new Intent (context, MyService.class);
intentt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startForegroundService(intentt);
} else {
Intent intentt = new Intent (context, MyService.class);
intentt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(intentt);
}
}
}
Service
public class MyService extends Service {
public static final String CHANNEL_ID = "exampleServiceChannel";
#Override
public void onCreate() {
super.onCreate();
Log.d("WhereAreWe", "create");
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.d("WhereAreWe", "StartCommand");
SharedPreferences check = getSharedPreferences("Checked", Context.MODE_PRIVATE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O){
Intent intents = new Intent(this, MainActivity.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intents, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "newid")
.setSmallIcon(R.drawable.ic_android)
.setContentTitle("Foreground Service")
.setContentText("Example text")
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent);
startForeground(1, builder.build());
}else{
startForeground(1, new Notification());
}
}
}
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.MyApplication">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
.
.
.
<receiver
android:name=".Restarter"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="restartservice" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false" />
</application>
</manifest>

Android service not working after reboot, giving ANR error

Went through the documentation on how to start a service automatically after the device boots and tried all they said but couldn't get my service to work after rebooting the device, though it works perfectly well on first instance.
Below is my main activity (MainActivity.java) which starts the service after a button has been clicked, and triggers the service every 10 seconds using AlarmManager.
public void onClickSubmitDate(View view) {
Intent service = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, service, 0);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, 10 * 1000, pendingIntent);
//Enable receiver when device boots
ComponentName receiver = new ComponentName(this, BootReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
Below is my receiver class (BootReceiver.java)
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Intent service = new Intent(context, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(null, 0, service, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
10 * 1000, 10 * 1000,
pendingIntent);
}
}
}
My service contains a thread which checks for multiple scenarios and builds a notification for each scenario. Here's a sample below:
public int onStartCommand(Intent intent, int flags, int startId) {
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
Runnable r = new Runnable() {
#Override
public void run() {
try {
boolean diff = true;
if (diff) {
// Build the notification
notification.setSmallIcon(R.drawable.icon);
notification.setTicker(getString(R.string.notification_ticker));
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle(getString(R.string.notification_title));
notification.setContentText(getString(R.string.notification_1_text));
notification.setSound(alarmSound);
Intent i = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
// Builds a notification and issues it
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Random r = new Random();
int rand = r.nextInt(1000);
nm.notify(rand, notification.build());
}
catch (Exception e) {
e.printStackTrace();
}
}
};
Thread stephThread = new Thread(r);
stephThread.start();
return START_STICKY;
}
And finally below is my AndroidManifest.xml code
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.motherslove.stephnoutsa.myapplication18calendartest"
android:installLocation="internalOnly">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyDate"
android:label="#string/title_activity_my_date"
android:theme="#style/AppTheme.NoActionBar" />
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />
<receiver
android:name=".BootReceiver"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
Please can someone tell me what I've done wrong?
Thanks to help from #MikeM I could fix the problem.
Instead of
PendingIntent pendingIntent = PendingIntent.getService(null, 0, service, 0);
I had to pass in the context as the first argument, in the receiver, as shown below
PendingIntent pendingIntent = PendingIntent.getService(context, 0, service, 0);

Categories