2011-11-14 32 views
0

这是我非常简单的代码:服务开始每5秒+ AlarmManager全自动停止并恢复

应用:

public class MainActivity extends Activity { 
/** Called when the activity is first created. */ 
public Intent myIntent; 
public Button OnButton; 
public Button OffButton; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    myIntent = new Intent(this, TimerService.class); 

    OnButton = (Button) findViewById(R.id.onbutton); 
    OffButton = (Button) findViewById(R.id.offbutton); 

    OnButton.setOnClickListener(new OnClickListener() 
    { 
     public void onClick(View v) 
     { 
      startService(myIntent); 
     } 
    }); 

    OffButton.setOnClickListener(new OnClickListener() 
    { 
     public void onClick(View v) 
     { 
      stopService(myIntent); 
     } 
    }); 
    } 
} 

服务:

public class TimerService extends Service 
{ 
public AlarmManager Alarmmgr; 
public PendingIntent myPendingIntent; 

@Override 
public void onCreate() 
{ 
    Alarmmgr = (AlarmManager) getSystemService(ALARM_SERVICE); 
} 

public void SimpleMethod() 
{ 
     //Here I will do something 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) 
{ 
    SimpleMethod(); 

    myPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
    Alarmmgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5000, myPendingIntent); 

    return Service.START_NOT_STICKY; 
} 

@Override 
public IBinder onBind(Intent intent) 
{ 
    return null; 
} 


@Override 
public void onDestroy() 
{ 
    Alarmmgr.cancel(myPendingIntent); 
} 

} 

的问题是,当我开始我的服务,并关闭它的工作30-50分钟的屏幕。在那段时间之后,它停下来10-50分钟,然后再次恢复......我想连续不间断地运行它。我在代码中必须更改什么?我尝试了一个计时器,但是当我关闭屏幕时它不起作用; /。

+0

尝试使你的服务[前景](http://developer.android.com/reference/android/app/Service.html) – yorkw

回答

0

也许你需要防止手机进入睡眠模式?

+0

你的意思是防止关闭我的屏幕或其他东西?我想知道为什么其他应用程序(不是我的)可以在后台工作,例如每5分钟保存一次文件。也许间隔太小?奇怪。 – krzysnick

+0

增加了wakelock,但我的服务有时仍在睡觉; /。我认为服务总是在后台运行,即使我的手机正在睡觉,但现在我发现这很难得到这种效果...... – krzysnick

+0

您是否尝试设置重复闹钟,而不是每次都设置闹钟?它不应该改变你所看到的行为,但是谁知道。 – zmbq