在这段代码中,我创建了一个服务.3秒后,我想要破坏这个服务,并希望在destroy方法中调用另一个活动。但这似乎不起作用。
public class TimerService extends Service
{
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onCreate()
{
super.onCreate();
}
@Override
public int onStartCommand(Intent intent,int flags,int startId)
{
new CountDownTimer(3000, 1000)
{
public void onTick(long millisUntilFinished)
{
}
public void onFinish()
{
stopSelf();
}
}.start();
return super.onStartCommand(intent,flags,startId);
}
@Override
public void onDestroy()
{
super.onDestroy();
Intent i = new Intent(this,Dummy.class);
i.putExtra("SessionTimedOut","Expire");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(i);
}
}
调用我的服务的活动
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this,TimerService.class);
startService(i);
}
}
答案 0 :(得分:1)
尝试将代码插入到finish方法中:
@Override
public int onStartCommand(Intent intent,int flags,int startId)
{
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(this,Dummy.class);
i.putExtra("SessionTimedOut","Expire");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
stopSelf();
}
}, 3000);
return super.onStartCommand(intent,flags,startId);
}