如何在30分钟内运行一次我的服务?

时间:2013-05-02 10:43:37

标签: android background-service

任何人都可以在半小时内告诉我一个简单的方法来运行服务吗?

这不是正常工作,任何人都可以在半小时内说出如何运行它。

我使用它在系统启动时启动我的应用程序,即使这不起作用..?

我这样做:

autostart.java

public class autostart extends BroadcastReceiver 
{
    public void onReceive(Context arg0, Intent arg1) 
    {
        Intent intent = new Intent(arg0,back_process.class);
        arg0.startService(intent);
        Log.i("Autostart", "started");
    }
}

Back_Process.java

 public class gps_back_process extends Service
    {
        private static final String TAG = "MyService";
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
        public void onDestroy() {

            Toast.makeText(this, "SERVICE STOPPED ..!", Toast.LENGTH_LONG).show();
            Log.d(TAG, "onDestroy");
        }

        @Override
        public void onStart(Intent intent, int startid)
        {
            Intent intents = new Intent(getBaseContext(),MainActivity.class);
            intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intents);
            Toast.makeText(this, "SERVICE STARTED", Toast.LENGTH_LONG).show();
            Log.d(TAG, "onStart");
        }
    }

谢谢!

2 个答案:

答案 0 :(得分:1)

使用AlarmManager及其方法setRepeating()。前段时间我问similar question。我的间隔时间是24小时,但是你的时间间隔是0.5小时,这是相同的故事。

答案 1 :(得分:1)

试试这个:

private AlarmManager alarmMgr;
private PendingIntent alarmIntent;

alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() +
        60 * 1000, alarmIntent);