17

我在互联网上搜索了过去 2 天,但找不到任何有用的教程。我已经创建了一项服务,并在服务启动时在状态栏中发送通知。我希望该服务在显示通知后停止,并在 5 分钟后重新启动。如果可能,请告诉我,如果您有任何有用的教程,请告诉我。我听说过TimerTask并且AlarmManager我也尝试使用它们,但我无法获得预期的结果。

编辑:即使我的应用程序没有运行,我也需要每 5 分钟启动一次服务。

4

3 回答 3

25

您不想使用 a TimerTask,因为这取决于您的应用程序是否连续运行。一个AlarmManager实现使您的应用程序在执行之间被杀死是安全的。

说您尝试使用AlarmManager但没有得到想要的结果并不是一个有用的陈述,因为它不会告诉任何人如何帮助您获得正确的结果。表达发生的事情会更有用。

http://web.archive.org/web/20170713001201/http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/包含关于AlarmManager. 以下是要点:

1)您的警报将Intent在到期时触发。由您决定应该采用哪种方式Intent以及如何实施。我提供的链接有一个基于广播接收器的完整示例。

2)您可以通过以下示例安装警报:

public void setOnetimeTimer(Context context) {
    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.TRUE);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * 5), pi);
}
于 2012-12-11T12:49:28.823 回答
13

下面我提供了三个文件,MainActivity.java 用于启动服务,第二个文件 MyService.java 提供 5 分钟服务,第三个文件是清单文件。

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, MyService.class)); //start service which is MyService.java
    }
}

我的服务.java

 public class MyService extends Service {

    public static final int notify = 300000;  //interval between two services(Here Service run every 5 Minute)
    private Handler mHandler = new Handler();   //run on another Thread to avoid crash
    private Timer mTimer = null;    //timer handling

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        if (mTimer != null) // Cancel if already existed
            mTimer.cancel();
        else
            mTimer = new Timer();   //recreate new
        mTimer.scheduleAtFixedRate(new TimeDisplay(), 0, notify);   //Schedule task
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTimer.cancel();    //For Cancel Timer
        Toast.makeText(this, "Service is Destroyed", Toast.LENGTH_SHORT).show();
    }

    //class TimeDisplay for handling task
    class TimeDisplay extends TimerTask {
        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // display toast
                    Toast.makeText(MyService.this, "Service is running", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}

AndroidManifest.xml

  <service android:name=".MyService" android:enabled="true" android:exported="true"></service>
于 2016-12-28T11:05:06.927 回答
-4

创建一个Timer对象并给它一个TimerTask执行您想要执行的代码的对象。

Timer timer = new Timer ();
TimerTask hourlyTask = new TimerTask () {
    @Override
    public void run () {
        // your code here...
    }
};

// schedule the task to run starting now and then every hour...
timer.schedule (hourlyTask, 0l, 1000*60*60);   // 1000*10*60 every 10 minut

使用 Timer 对象的优点是它可以处理多个 TimerTask 对象,每个对象都有自己的计时、延迟等。您还可以通过将 Timer 对象声明为类来启动和停止计时器变量什么的。

于 2012-12-11T12:42:34.373 回答