我怎样才能在特定时间之后每次都在android中调用一个方法(循环)

时间:2016-01-23 07:24:16

标签: android multithreading

我想在每5秒后调用一个方法,但它只在应用程序启动时运行一次

     super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
     Handler delayhandler = new Handler();
     Runnable run = new Runnable() {
        @Override
        public void run() {
            loop();

        }
    };
    delayhandler.postDelayed(run, 5000);
     }

   void loop(){

  Toast.makeText(MainActivity.this, "ooh", Toast.LENGTH_SHORT).show();
  }

3 个答案:

答案 0 :(得分:1)

 Handler delayhandler = new Handler();
     Runnable run = new Runnable() {
        @Override
        public void run() {
            loop();

        }
    };
    delayhandler.postDelayed(run, 5000);
     }

   void loop(){
  Toast.makeText(MainActivity.this, "ooh", Toast.LENGTH_SHORT).show();
delayhandler.postDelayed(run, 5000);
  }

答案 1 :(得分:1)

创建方法:

public void setAlarm(Context context, int interva) {
    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent i = new Intent(context, NotificationAlarm.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interva, pi); 
}

然后创建类NotificationAlarm

public class NotificationAlarm extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        loop();
    }

    private void loop() {
    //work
    }
}

在AndroidManifest中添加该类

<receiver android:name=".NotificationAlarm" />

在活动或服务中调用方法

setAlarm(this,5000);

for cancelAlarm试试这个:

public void cancelAlarm(Context context) {

    Intent intent = new Intent(context, NotificationAlarm.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    alarmManager = (AlarmManager) G.context.getSystemService(G.context.ALARM_SERVICE);
    alarmManager.cancel(pendingIntent);
}

答案 2 :(得分:0)

你可以使用Timer任务,就像这样,

private Timer timer;
private TimerTask timerTask = new TimerTask() {

    @Override
    public void run() {
        final Random random = new Random();
        int i = random.nextInt(2 - 0 + 1) + 0;
        random_note.setImageResource(image[i]);
    }
};

public void start() {
    if(timer != null) {
        return;
    }
    timer = new Timer();
    timer.scheduleAtFixedRate(timerTask, 0, 2000);
}

public void stop() {
    timer.cancel();
    timer = null;
}