0

我正在开发 android 应用程序,我想在每 10 秒后做一些事情。甚至应用程序都关闭了。为此,我实现了一个后台服务,它为我执行后台任务。我的代码结构如下所示:

// my main activity
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button start = (Button)findViewById(R.id.serviceButton);
        Button stop = (Button)findViewById(R.id.cancelButton);

        start.setOnClickListener(startListener);
        stop.setOnClickListener(stopListener);

   }

   private OnClickListener startListener = new OnClickListener() {
    public void onClick(View v){
        startService(new Intent(SimpleServiceController.this,SimpleService.class));
    }               
   };

   private OnClickListener stopListener = new OnClickListener() {
        public void onClick(View v){
            stopService(new Intent(SimpleServiceController.this,SimpleService.class));
        }               
      }; 


//simpleservice

   @Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
}


@Override
public void onDestroy() {
    super.onDestroy();
    Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
}

这工作正常。但是,当我每 10 秒后开始服务时,我现在想要做的只是给我简单的 Toast 消息,当我停止服务时停止 Toast 消息。

我也尝试过使用 AlarmManager。

// main activity....
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

public void startAlert(View view) {

    Intent intent = new Intent(this, MyBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this.getApplicationContext(), 234324243, intent, 0);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
            + (10 * 1000), pendingIntent);
    Toast.makeText(this, "Alarm set in " + 10 + " seconds",
            Toast.LENGTH_LONG).show();
}



// broadcast receiver
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Don't panik but your time is up!!!!.",
            Toast.LENGTH_LONG).show();

}

}

但我不能定期这样做。实现这一点的正确方法是什么?需要帮助...谢谢...

4

1 回答 1

-2

你需要这样的东西:

while (connected){

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        public void run() {
            Toast.makeText(this, "Hi", Toast.LENGTH_SHORT).show();
        }
    }, 10000);
}

并且 connected 是一个布尔值,您可以在停止方法上进行更改

于 2012-08-13T10:57:38.847 回答