在android中创建一个预定服务

El *_*7eR 4 java service android schedule bluetooth

我需要在android中用java创建一个日程安排服务.我已经尝试了一些代码,但是在构建应用程序之后它一直没有运行.我的逻辑很简单,我想做一个服务来检查蓝牙文件夹路径中是否存在文件,如果这个文件在那里,那么这个服务将运行另一个应用程序,我需要这个,每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);
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我这个.

Luc*_*fer 9

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

  • 的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
         } 
    }
    
    Run Code Online (Sandbox Code Playgroud)

    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();
            }
       }
    }
    
    Run Code Online (Sandbox Code Playgroud)

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 );
Run Code Online (Sandbox Code Playgroud)

  • 如何解决它,以便即使在用户关闭应用程序后它也会运行? (2认同)