Search code examples
javaandroidbroadcastreceiveralarmmanager

Android loop service every 5 seconds and boot on startup


I have the code below and I want to loop this every 5 seconds. I have tried to use broadcastreceiver and alarm manager but without success . I want my service to loop for 5 times and after that stop permanently .This is the second question I post . Please somebody help me to fix the code, I am stacked on my mac for 2 days. Any help will be appreciated.

Code to loop every 5 seconds

File key = new File(Environment.getExternalStorageDirectory(),"newfile"+Math.random()+".txt");
try {
    key.createNewFile();
} catch (IOException e) {
    e.printStackTrace();
}

InfoReceiver.class Service

public class InfoReceiver extends Service {

    @Override
    public void onCreate()
    {
        AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, MyBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        Calendar time = Calendar.getInstance();
        time.setTimeInMillis(System.currentTimeMillis());
        time.add(Calendar.SECOND, 5);
        alarmMgr.set(AlarmManager.RTC_WAKEUP, 5000, pendingIntent);
    }
}

InfoManager.class service

public  class InfoManager extends Service {
    @Override
    public void onCreate() {
        File key = new File(Environment.getExternalStorageDirectory(),"newfile"+Math.random()+".txt");
        try {
            key.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

MyBroadcastreceiver.class

public class MyBroadcastReceiver extends BroadcastReceiver {
    private Context mContext;
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent startServiceIntent = new Intent(context, InfoManager.class);
        context.startService(startServiceIntent);
    }
}

Manifest Code

<service
    android:name=".InfoReceiver"
    android:enabled="true" >
</service>
<service
    android:name=".InfoManager"
    android:enabled="true" >
    <intent-filter>
        <action android:name=".InfoManager" />
    </intent-filter>
</service>
<receiver
    android:name=".MyBroadcastReceiver"
    android:process=":remote" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

Solution

  • Use Handler.postDelayed(Runnable r, long delayMillis). You don't need timers or the alarm manager to do what you want. Stay simple.