【问题标题】:Create a Scheduled service in android在android中创建一个计划服务
【发布时间】:2012-09-27 10:59:00
【问题描述】:

我需要用java在android中创建一个调度服务。我已经尝试了一些代码,但是在构建应用程序之后它一直没有运行。我的逻辑很简单,我想创建一个服务来检查蓝牙文件夹路径中是否存在一个文件,如果这个文件存在,那么这个服务将运行另一个应用程序,我需要一个每 2 分钟运行一次的计划。

到目前为止,这很好,但现在我有一个错误The method startActivity(Intent) is undefined for the type MyTimerTask。我试过这段代码...

public class MyTimerTask extends TimerTask {
    java.io.File file = new java.io.File("/mnt/sdcard/Bluetooth/1.txt");

    public void run(){ 
        if (file.exists()) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setComponent(new ComponentName("com.package.address","com.package.address.MainActivity"));
            startActivity(intent);
        }
    } 
}

有人可以帮我解决这个问题吗?

【问题讨论】:

标签: java android service bluetooth schedule


【解决方案1】:

有两种方法可以满足您的要求。

  • 定时器任务
  • 报警管理器类

    TimerTask 有一个方法可以在给定的特定时间间隔内重复活动。请看下面的示例。

    Timer timer; 
    MyTimerTask timerTask; 
    
    timer = new Timer(); 
    timerTask = new MyTimerTask();
    timer.schedule ( timerTask, startingInterval, repeatingInterval );
    
    private class MyTimerTask extends TimerTask 
    {
         public void run()
         { 
            ...
            // Repetitive Activity goes here
         } 
    }
    

    AlarmManagerTimerTask 做同样的事情,但它占用更少的内存来执行任务。

    public class AlarmReceiver extends BroadcastReceiver 
    {
        @Override
        public void onReceive(Context context, Intent intent) 
        {
            try 
            {
                Bundle bundle = intent.getExtras();
                String message = bundle.getString("alarm_message");
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            } 
            catch (Exception e) 
            {
                 Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
     e.printStackTrace();
            }
       }
    }
    

报警类,

private static Intent alarmIntent = null;
private static PendingIntent pendingIntent = null;
private static AlarmManager alarmManager = null;

    // OnCreate()
    alarmIntent = new Intent ( null, AlarmReceiver.class );
    pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), 234324243, alarmIntent, 0 );
alarmManager = ( AlarmManager ) getSystemService( ALARM_SERVICE );
    alarmManager.setRepeating( AlarmManager.RTC_WAKEUP, ( uploadInterval * 1000 ),( uploadInterval * 1000 ), pendingIntent );

【讨论】:

  • +1 我喜欢您的 AlarmManager 建议,利用原生 Android 类/方法。
  • timerTask = new MyTimerTask();对不起拼写错误。但我建议你去警报类。
  • 如何修复它,即使在用户关闭应用后它也能运行?
  • @Lucifer 我想你错过了广播接收器的清单条目。具体来说,提到将唤醒接收者的意图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 2015-03-14
  • 1970-01-01
  • 2011-06-04
  • 2021-09-18
  • 2015-09-16
相关资源
最近更新 更多