如何在Android中从服务类结束活动?

17
我正在开发一个应用程序,希望在后台从服务器获取数据。我使用服务在后台获取数据。现在我想处理网络异常,如果没有网络,我想显示一个警示对话框并结束应用程序。但我遇到了一个问题,即在服务类中完成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();
            }               
        }
    }
}

你可以通过 Binder 或广播接收器实现它。 - Sekhar Madhiyazhagan
2个回答

27

在这行代码中:

((Activity) mContext).finish();

mContext 是从 new InitialRequestData(InitialRequestService.this).execute(); 中来的,它是来自 InitialRequestService 而不是 Activity,因此会出现 ClassCastException 异常。

您需要将 Activity 实例传递给 Service。但是我更喜欢在您的 InitialRequestService 中像这样向 Activity 发送一个 BroadcastReceiver:

alert.setButton("OK", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which) {

        alert.dismiss();
        // modify here
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager
                .getInstance(InitialRequestService.this);
        localBroadcastManager.sendBroadcast(new Intent(
                "com.durga.action.close"));
                }
            });

在您想要关闭的Activity中:

public class YourActivity extends Activity{

    LocalBroadcastManager mLocalBroadcastManager;
    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("com.durga.action.close")){
                finish();
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction("com.durga.action.close");
        mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, mIntentFilter);
    }

    protected void onDestroy() {
        super.onDestroy();
        mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
    }
}
希望能有所帮助。

是的,你说的原因是正确的。但我无法理解你的解决方案。请告诉我如何修改我的代码以解决这个问题。 - Durga
1
谢谢你非常感谢,它正在运行中。感谢你为我花费时间。 - Durga

1
我认为您需要像以下这样从服务中传递简单的意图
Intent myIntent = new Intent(First.this,Secound.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle myKillerBundle = new Bundle();
myKillerBundle.putInt("kill",1);
myIntent.putExtras(myKillerBundle);
getApplication().startActivity(myIntent);

然后在 Secound.class 中。
onCreate(Bundle bundle){
if(this.getIntent().getExtras().getInt("kill")==1)
    finish();
}

否则使用BroadcastReceiver。请参见下面的示例。

如何从服务中关闭活动?

希望它有效。

我正在使用这些值来计算整个应用程序,而不是单个类。 - Durga
我的第二个类是服务类,所以我必须在服务类中完成活动。 - Durga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接