我的工作我的第一个Android应用程序和我有业务的问题,定时器将无法正常工作。我有一个活动和一个服务,在活动中有一个按钮,在服务和服务中调用一个方法,我有一个计时器,在20秒后在Logcat中显示一些东西。在活动中,我使用startService(intet)启动服务,然后绑定到该服务,以便即使在关闭许多主题中的建议后仍然可以继续工作。绑定服务正在运行,但如果我关闭应用程序
如果我点击后退按钮或主页按钮,应用程序可以正常工作,但是如果我按住主页按钮,然后关闭应用程序,我看不到日志,但是如果我在“运行”选项卡下进入应用程序管理器,我可以看到我的应用程序和服务正在运行!
我不想使用警报管理器。我在这里使用计时器的原因是我想确保我的服务真的有效!我只想在服务中做一些事情,并确保它即使在应用程序关闭时也能正常工作。
public class BoundService extends Service {
private final IBinder myBinder = new MyLocalBinder();
@Override
public IBinder onBind(Intent intent) {
return myBinder;
}
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}
@Override
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
public void testNotification()
{
int interval = 20000; // 20 Second
Handler handler = new Handler();
Runnable runnable = new Runnable(){
public void run() {
Log.d("BoundService", "Timer");
}
};
handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);
}
public class MyLocalBinder extends Binder {
BoundService getService() {
return BoundService.this;
}
}
}
活动:
public class MainActivity extends Activity {
BoundService myService;
boolean isBound = false;
public void test(View view)
{
myService.testNotification();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, BoundService.class);
startService(intent);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
MyLocalBinder binder = (MyLocalBinder) service;
myService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
感谢
您是否找到任何解决方案? –