我正确地启动了我的服务,它运行良好。我写的条件是,如果服务已经在运行,那么它不会再次启动服务。条件返回表明服务正在运行的真值。但是每当我强制停止我的应用程序,或者如果发生任何异常,我的服务就会停止在后台加载数据,直到显示该服务正在运行。这就是服务没有重新启动的原因。
我曾经从活动开始服务的意图:
this.startService(new Intent(MainMenu1.this, MovieService.class));
我的服务等级是:
公共类 MovieService 扩展服务 {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TBD
Log.i("Movie Service : "," Created2");
new MovieDownloaderTask().execute();
return Service.START_FLAG_REDELIVERY;
//return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
Log.i("Movie Service : "," Created");
}
@Override
public void onDestroy() {
Log.d("Movie Service","onDestroy was Called!");
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startid) {
Log.i("Movie Service : "," Started");
}
public class MovieDownloaderTask extends AsyncTask<Void, Void, Integer>
{
@Override
protected Integer doInBackground(Void... params) {
Log.i("Movie Service"," : Started2");
//Moviejson.createDB();
try
{
Moviejson.insert_Movie_Data();
}
catch(Exception e)
{
Log.e("Exception > ", "i m in doInBackground. Trying to stop Movie service.");
MovieService.this.stopSelf();
e.printStackTrace();
}
return 1;
}
@Override
protected void onPostExecute(Integer result) {
if (result == 1) {
if(MainMenu1.Movies_new_time==null)
{
MainMenu1.Movies_new_time=MainMenu1.sp.getMovies_Old_Date();
}
else
{
MainMenu1.sp.setMovies_Current_Date(MainMenu1.Movies_new_time);
}
MainMenu1.sp.setMovies_Current_Date(MainMenu1.Movies_new_time);
Log.i("Movie Date:", " : "+MainMenu1.Movies_new_time);
MovieService.this.stopSelf();
Log.i("Movie Service"," : Stoped");
super.onPostExecute(result);
}
}
}
}