2012-08-30 21 views
4

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

直到现在,这是伟大的,但现在我有一个错误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); 
     } 
    } 
} 

有人可以帮我这个。

+0

请发表你试过吗? –

+0

因为你是新用户,我建议你访问[如何接受答案](http://meta.stackexchange.com/a/65088) – Lucifer

回答

8

有两种方法可以实现您的要求。

  • 的TimerTask
  • 报警管理器类

    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 
        } 
    } 
    

    AlarmManager做同样的事情,就像TimerTask但因为它占用较少的内存来执行任务。

    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(); 
         } 
        } 
    } 
    

AlarmClass报警,

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

+1我喜欢你的AlarmManager建议,利用原生Android类/方法。 – Syntax

+0

timerTask = new MyTimerTask();抱歉错字错误。但我建议你去报警类。 – Lucifer

+1

@Lucifer,使用Alarm时应该如何显示? – eeadev