1

I want every minute to push a notifaction and a tried this: https://stackoverflow.com/a/8801990

But the problem is, that the alarm doesn't run. I tried to set Logs but I can't see them...

Now I've started a new project and here are my files, maybe one import is wrong, but I don't know...:

MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //startService(new Intent(this, YourService.class));
        Log.e("MainActivity", "onCreate");
    }
}

Alarm.java

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;


public class Alarm extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();

        // Put here YOUR code.
        Log.e("Alarm", "onReceive");
        Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

        wl.release();
    }

    public void setAlarm(Context context)
    {
        Log.e("Alarm", "setAlarm");
        AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, Alarm.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        // Changed to 1 minute
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 1, pi); // Millisec * Second * Minute
    }

    public void cancelAlarm(Context context)
    {
        Intent intent = new Intent(context, Alarm.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }
}

YourService.java

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class YourService extends Service
{
    Alarm alarm = new Alarm();
    public void onCreate()
    {
        Log.e("Service", "onCreate");
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Log.e("Service", "onStartCommand");
        alarm.setAlarm(this);
        return START_STICKY;
    }
    @Override
    public void onStart(Intent intent, int startId)
    {
        alarm.setAlarm(this);
    }
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }
}

It's the same code like in the link, i just only changed the time to one minute... Here is my Manifest.xml:

<?xml version="1.0" encoding="utf-8"?>

<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">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <!--AutoStart Receiver -->
    <receiver android:name="com.example.alarm.alarmmanagertest.AutoStart">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"></action>
        </intent-filter>
    </receiver>

    <!-- Receiver and Permisson added -->
    <receiver android:process=":remote" android:name="com.example.alarm.alarmmanagertest.Alarm"></receiver>
    <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

    <!-- Added my Service -->
    <service
        android:name=".YourService"
        android:enabled="true"
        android:process=":your_service" >
    </service>
</application>

There is nothing in the Android Monitor like "E/Alarm: onReceive" and for example the toast also doesn't start. To be honest I tried everything, also tried this here: http://it-ride.blogspot.de/2010/10/android-implementing-notification.html

Could someone help me please and is it the right way to push a notification? Using API 16 now...

App Logcat:

11-02 21:48:19.234 3433-3433/? D/dalvikvm: Late-enabling CheckJNI
11-02 21:48:19.726 3433-3433/com.example.alarm.alarmmanagertest I/dalvikvm: Could not find method android.app.Application.registerOnProvideAssistDataListener, referenced from method com.android.tools.fd.runtime.BootstrapApplication.registerOnProvideAssistDataListener
11-02 21:48:19.726 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve virtual method 234: Landroid/app/Application;.registerOnProvideAssistDataListener (Landroid/app/Application$OnProvideAssistDataListener;)V
11-02 21:48:19.726 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-02 21:48:19.726 3433-3433/com.example.alarm.alarmmanagertest I/dalvikvm: Could not find method android.app.Application.unregisterOnProvideAssistDataListener, referenced from method com.android.tools.fd.runtime.BootstrapApplication.unregisterOnProvideAssistDataListener
11-02 21:48:19.726 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve virtual method 237: Landroid/app/Application;.unregisterOnProvideAssistDataListener (Landroid/app/Application$OnProvideAssistDataListener;)V
11-02 21:48:19.726 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-02 21:48:19.726 3433-3433/com.example.alarm.alarmmanagertest I/InstantRun: Instant Run Runtime started. Android package is com.example.alarm.alarmmanagertest, real application class is null.
11-02 21:48:19.734 3433-3433/com.example.alarm.alarmmanagertest W/InstantRun: No instant run dex files added to classpath
11-02 21:48:19.742 3433-3433/com.example.alarm.alarmmanagertest E/dalvikvm: Could not find class 'android.util.ArrayMap', referenced from method com.android.tools.fd.runtime.MonkeyPatcher.monkeyPatchExistingResources
11-02 21:48:19.742 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve check-cast 1886 (Landroid/util/ArrayMap;) in Lcom/android/tools/fd/runtime/MonkeyPatcher;
11-02 21:48:19.742 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x1f at 0x025e
11-02 21:48:19.742 3433-3433/com.example.alarm.alarmmanagertest E/dalvikvm: Could not find class 'android.util.ArrayMap', referenced from method com.android.tools.fd.runtime.MonkeyPatcher.pruneResourceCache
11-02 21:48:19.742 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve const-class 1886 (Landroid/util/ArrayMap;) in Lcom/android/tools/fd/runtime/MonkeyPatcher;
11-02 21:48:19.742 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x1c at 0x0060
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest I/dalvikvm: Could not find method android.view.Window$Callback.onProvideKeyboardShortcuts, referenced from method android.support.v7.view.WindowCallbackWrapper.onProvideKeyboardShortcuts
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve interface method 16034: Landroid/view/Window$Callback;.onProvideKeyboardShortcuts (Ljava/util/List;Landroid/view/Menu;I)V
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve interface method 16036: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve interface method 16040: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve virtual method 721: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve virtual method 743: Landroid/content/res/TypedArray;.getType (I)I
11-02 21:48:20.101 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x6e at 0x0008
11-02 21:48:20.437 3433-3433/com.example.alarm.alarmmanagertest I/dalvikvm: Could not find method android.widget.FrameLayout.startActionModeForChild, referenced from method android.support.v7.widget.ActionBarContainer.startActionModeForChild
11-02 21:48:20.437 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve virtual method 16467: Landroid/widget/FrameLayout;.startActionModeForChild (Landroid/view/View;Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
11-02 21:48:20.437 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x6f at 0x0002
11-02 21:48:20.453 3433-3433/com.example.alarm.alarmmanagertest I/dalvikvm: Could not find method android.content.Context.getColorStateList, referenced from method android.support.v7.content.res.AppCompatResources.getColorStateList
11-02 21:48:20.453 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve virtual method 449: Landroid/content/Context;.getColorStateList (I)Landroid/content/res/ColorStateList;
11-02 21:48:20.453 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
11-02 21:48:20.460 3433-3433/com.example.alarm.alarmmanagertest I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawable
11-02 21:48:20.460 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve virtual method 684: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
11-02 21:48:20.460 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-02 21:48:20.460 3433-3433/com.example.alarm.alarmmanagertest I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawableForDensity
11-02 21:48:20.460 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve virtual method 686: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
11-02 21:48:20.460 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-02 21:48:20.476 3433-3433/com.example.alarm.alarmmanagertest E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
11-02 21:48:20.476 3433-3433/com.example.alarm.alarmmanagertest W/dalvikvm: VFY: unable to resolve instanceof 149 (Landroid/graphics/drawable/RippleDrawable;) in Landroid/support/v7/widget/AppCompatImageHelper;
11-02 21:48:20.476 3433-3433/com.example.alarm.alarmmanagertest D/dalvikvm: VFY: replacing opcode 0x20 at 0x000c
11-02 21:48:20.648 3433-3438/com.example.alarm.alarmmanagertest D/dalvikvm: GC_CONCURRENT freed 235K, 20% free 5386K/6664K, paused 5ms+6ms, total 32ms
11-02 21:48:20.656 3433-3433/com.example.alarm.alarmmanagertest E/MainActivity: onCreate
11-02 21:48:20.906 3433-3433/com.example.alarm.alarmmanagertest D/libEGL: loaded /system/lib/egl/libEGL_MRVL.so
11-02 21:48:20.960 3433-3433/com.example.alarm.alarmmanagertest D/libEGL: loaded /system/lib/egl/libGLESv1_CM_MRVL.so
11-02 21:48:20.976 3433-3433/com.example.alarm.alarmmanagertest D/libEGL: loaded /system/lib/egl/libGLESv2_MRVL.so
11-02 21:48:20.992 3433-3433/com.example.alarm.alarmmanagertest D/GC: <tid=3433> OES20 ===> GC Version   : GC Ver SS_rls_pxa988_JB42_R1_RC2_GC13.15 
11-02 21:48:21.046 3433-3433/com.example.alarm.alarmmanagertest D/OpenGLRenderer: Enabling debug mode 0

Non-App Logcat:

1-02 21:59:45.765 515-617/? V/AlarmManager: trigger ELAPSED_REALTIME_WAKEUP or RTC_WAKEUP
11-02 21:59:49.914 515-592/? I/Monitor: SIOP:: Current AP = 380, CP = 0, PST = 380
11-02 21:59:52.914 515-607/? D/BatteryService: update start
11-02 21:59:52.921 515-607/? D/BatteryService: level:100, scale:100, status:3, health:2, present:true, voltage: 4325, temperature: 220, technology: Li-ion, AC powered:false, USB powered:true, Wireless powered:false, icon:17303457, invalid charger:0, online:4, charge type:1, current avg:450
11-02 21:59:52.921 515-592/? D/BatteryService: Sending ACTION_BATTERY_CHANGED.
11-02 21:59:52.929 775-775/? D/STATUSBAR-BatteryController: onReceive() - ACTION_BATTERY_CHANGED
11-02 21:59:52.929 775-775/? D/STATUSBAR-BatteryController: onReceive() - BATTERY_STATUS_DISCHARGING: tw_stat_sys_battery_usb_not_charge
11-02 21:59:52.953 775-775/? D/STATUSBAR-IconMerger: checkOverflow(390), More:false, Req:false Child:13
11-02 21:59:52.968 775-775/? D/STATUSBAR-PhoneStatusBar:  mBrightnessEnablebySettings = true mBrightnessEnablebyBattery = true mBrightnessEnablebyDisableFlag = true
11-02 21:59:57.664 515-615/? I/PowerManagerService: [PWL] Off : 105s ago
11-02 21:59:59.921 515-592/? I/Monitor: SIOP:: Current AP = 380, CP = 0, PST = 380
11-02 21:59:59.992 515-617/? V/AlarmManager: waitForAlarm result :8
11-02 22:00:00.007 3817-3817/? D/KeyguardClockWidgetService: onReceive action=android.intent.action.TIME_TICK
11-02 22:00:00.015 515-592/? V/AlarmManager: ClockReceiver onReceive() ACTION_TIME_TICK
11-02 22:00:00.054 775-775/? D/STATUSBAR-IconMerger: checkOverflow(390), More:false, Req:false Child:13
11-02 22:00:03.015 515-607/? D/BatteryService: update start
11-02 22:00:05.039 515-595/? W/ProcessStats: Skipping unknown process pid 14477
11-02 22:00:05.039 515-595/? W/ProcessStats: Skipping unknown process pid 14479
11-02 22:00:05.039 515-595/? W/ProcessStats: Skipping unknown process pid 14480
11-02 22:00:09.929 515-592/? I/Monitor: SIOP:: Current AP = 380, CP = 0, PST = 380
11-02 22:00:12.062 515-837/? E/Watchdog: !@Sync 1050
11-02 22:00:12.078 515-617/? V/AlarmManager: waitForAlarm result :4

You can see, that there is something from the AlarmManager, but I think it's from an other App. Should I unstill my other Apps where I tried to work with the AlarmManager and restart my device?

Community
  • 1
  • 1
HoriZoN
  • 23
  • 7
  • Where and how do you call `SetAlarm()`? – earthw0rmjim Nov 02 '16 at 12:27
  • I start the alarm with the service: alarm.setAlarm(this); or also with the AutoStart.java: if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { alarm.setAlarm(context); } you can see it here, I use the same code like here, just edited the time to one minute, added Logs and also maybe the manifest.xml is wrong... http://stackoverflow.com/questions/4459058/alarm-manager-example/8801990#8801990 – HoriZoN Nov 02 '16 at 12:42

2 Answers2

1

Your <receiver> block in the manifest for the Alarm broadcast receiver is incorrect. The name attribute needs the FQN of the class or the shorthand ".Alarm", assuming that the class is part of the package declared at the top of the manifest file.

Larry Schiefer
  • 15,687
  • 2
  • 27
  • 33
  • Thank you! That's true, but it wasn't the solution :/ Now I've started a new project and also updated my question. – HoriZoN Nov 02 '16 at 18:26
  • Check the logcat, it should show some useful information. Turn off any app specific filtering and look at the raw logcat output. Unless you have a specific need, you may want to remove the `android:process` attribute from the broadcast receiver (and service) declarations in the manifest. It's possible that could be interfering with `Toast` being shown on screen (though not very likely.) – Larry Schiefer Nov 02 '16 at 18:38
  • Okay thanks, i added the logcat output. And also removed the `android:process` and it's still the same... – HoriZoN Nov 02 '16 at 20:44
  • Is your `Service` ever actually running and setting the alarm? This article may help you: http://po.st/7UpipA. It doesn't take into account doze mode (Marshmallow+), but covers the basics and has demo code. – Larry Schiefer Nov 03 '16 at 10:53
  • Thank you Larry :) – HoriZoN Nov 03 '16 at 20:00
1

So guys I tried this one and it finally worked!

http://stacktips.com/tutorials/android/repeat-alarm-example-in-android

So if you want to run an AlarmManager and send a Notificiation, that opens your Application by clicking on it, here is the code:

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <!-- Permission to start Alarm on device reboot -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

    <activity
        android:name="alarmservice.javatechig.com.alarmservice.MyActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name="alarmservice.javatechig.com.alarmservice.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="alarmservice.javatechig.com.alarmservice.DeviceBootReceiver"
        android:enabled="false">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>

</application>

MyActivity.java

 import android.app.Activity;
 import android.app.AlarmManager;
 import android.app.PendingIntent;
 import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.widget.Toast;
 import java.util.Calendar;

 public class MyActivity extends Activity {

 private PendingIntent pendingIntent;

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

    /* Retrieve a PendingIntent that will perform a broadcast */
    Intent alarmIntent = new Intent(MyActivity.this, AlarmReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(MyActivity.this, 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);
    Log.e("Alarm","started");
    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, 13);
    calendar.set(Calendar.MINUTE, 27);

    /* Repeating on every 20 minutes interval */
    manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            1000 * 60 * 20, pendingIntent);
}

}

DeviceBootReceiver.java

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;


/**
 * @author Neel
 *         <p/>
 *         Broadcast reciever, starts when the device gets starts.
 *         Start your repeating alarm here.
 */
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();
        }
    }
}

AlarmReceiver.java

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;


public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        showNotification(context);
        System.out.println("running");
        Log.e("Alarm","running");

        // For our recurring task, we'll just display a message
        Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
    }

    private void showNotification(Context context) {
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MyActivity.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("My notification")
                        .setContentText("Finally");
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());

    }
}

The Source again: http://stacktips.com/tutorials/android/repeat-alarm-example-in-android Some tips:

  • in <receiver android:name=""> write the whole name
  • don't forget the uses-permission
  • start a new project, insert this code and try to unterstand how it works
  • after that you can put in your project
HoriZoN
  • 23
  • 7