我对Android中的服务感到困惑

时间:2012-09-16 14:53:22

标签: android android-service android-alarms

我有一个很大的程序,有很多表单,并与数据库等一起工作。我有一个警报作为我的程序的一部分。当我在10-20秒后触发警报并清理内存(在任务管理器中)时,警报会触发事件(即使时间尚未到达)。如果我将警报作为独立软件运行 - 它运行得很完美!

警报不能成为程序的一部分吗?或者可能是什么问题?

这就是我使用闹钟的方式:

    MY_Day=1;
    Intent myIntent = new Intent(MyService.this, MyAlarmService.class);
    pendingIntent = PendingIntent.getService(MyService.this, 0, myIntent, 0);
    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, MY_Houre);
    cal.set(Calendar.MINUTE, MY_Minute);
    cal.set(Calendar.SECOND, 0);
    Total_Time = MY_Day * AlarmManager.INTERVAL_DAY;
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), Total_Time, 
pendingIntent);

这是我的服务:

public class MyAlarmService extends Service {
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
    Toast toast = Toast.makeText(getApplicationContext(), "MyEvent",   Toast.LENGTH_LONG);
   toast.setGravity(Gravity.CENTER, 0, 0);
   LinearLayout toastView = (LinearLayout) toast.getView();
   ImageView imageCodeProject = new ImageView(getApplicationContext());
   imageCodeProject.setImageResource(R.drawable.koko);
   toastView.addView(imageCodeProject, 0);
   toast.show();
}

1 个答案:

答案 0 :(得分:2)

重新考虑您的代码并阅读Vogella Service Tutorial以获取有关服务的更多信息。

相关问题