这是我非常简单的代码:
应用:
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 :(得分:0)
也许您需要阻止手机进入睡眠模式?