我需要用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);
}
}
}
有人可以帮我解决这个问题吗?
有两种方法可以实现您的要求。
- 定时任务
-
报警管理类
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();
}
}
}
警报类,
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 );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)