Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

java - schedule two tasks subsequently in android

i want to perform 2 tasks. First should repeat once in every 10min Second should repeat every minute. Example Opening a website in first task Opening another website in second task. Thanx in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For the scheduling part you can use the AlarmManager

For instance:

public class TaskScheduler {
    public static void startScheduling(Context context) {

            Intent intent = new Intent(context, MyReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 600, pendingIntent);

    }
}

Then inside your receiver class you can start an IntentService:

public class MyReceiver extends BroadcastReceiver {    
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intentService = new Intent(context, MyService.class);
        context.startService(intentService);
    }
}

MyServicelooks roughly like:

class MyService extends IntentService {
    public MyService() { 
        super(MyService.class.getSimpleName());
    }

    @Override
    public void onHandleIntent(Intent intent) {
        // your code goes here
    }
}

And finally, don't forget to register MyReceiver in the manifest file:

<receiver 
   android:name="Your.Package.MyReceiver">
</receiver>

As well as your service:

<service 
   android:name="...">
</service>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...