我正在开发一个应用程序,希望在后台从服务器获取数据。我使用服务在后台获取数据。现在我想处理网络异常,如果没有网络,我想显示一个警示对话框并结束应用程序。但我遇到了一个问题,即在服务类中完成Activity会引发ClassCastException异常..这里引发了异常(((Activity) mContext).finish())。我尝试了很多次,但是我无法解决这个问题,请有经验的人帮忙解决一下我的问题。
public class InitialRequestService extends Service{
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
new InitialRequestData(InitialRequestService.this).execute();
}
public class InitialRequestData extends AsyncTask<String, Void, Void> {
public InitialRequestData(Context context) {
this.mContext = context;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
isNetworkAvailable = CheckNetWork.isConnectedToInternet(mContext);
}
@Override
protected Void doInBackground(String... params) {
//
}
@Override
protected void onPostExecute(FeatureResult result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result==null || isNetworkAvailable==false){
/*String message="Unable to connect to the server, please try again";
FieldsValdations.AlertErrorMessage(mContext, message, "Network failure");*/
final AlertDialog alert = new AlertDialog.Builder(mContext).create();
alert.setTitle("Network failure");
alert.setMessage("Unable to connect to the server, please try again");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.dismiss();
((Activity) mContext).finish();
}
});
alert.setCancelable(false);
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alert.show();
}
}
}
}