如何关闭服务中的活动?

pik*_*iks 17 android

我正在从服务启动活动,基于从服务器获得的一些值,活动将显示一段时间,在收到服务器的密切指令后,我需要关闭该活动,所以为此,我使用了以下方法,但它不是working:on Service class:

if(((ActivityManager)this.getSystemService(ACTIVITY_SERVICE)).getRunningTasks(1).get(0).topActivity.getPackageName().equals("com")) {

if(((ActivityManager)this.getSystemService(ACTIVITY_SERVICE)).getRunningTasks(1).get(0).topActivity.getClassName().equals("com.CustomDialogActivity")){
Intent dialogIntent = new Intent(getBaseContext(), CustomDialogActivity.class);
             dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);               
             dialogIntent.putExtra("description", "");
             dialogIntent.putExtra("cancelEnabled", false);
             dialogIntent.putExtra("close", true);
            getApplication().startActivity(dialogIntent);


}
    }
Run Code Online (Sandbox Code Playgroud)

以及onCreate方法中的活动:

Bundle bundle = getIntent().getExtras();
boolean isClosed = bundle.getBoolean("close");
    if(isClosed){        
        finish();
 }
Run Code Online (Sandbox Code Playgroud)

我调试它,发现控制到达onCreate方法if(isClosed)条件并执行finish()方法,但它没有关闭活动.

所以无法分析我在做什么错.

jai*_*nal 54

在CustomDialogActivity中编写广播接收器,如下所示.

private final BroadcastReceiver abcd = new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {
                   finish();                                   
             }
     };
Run Code Online (Sandbox Code Playgroud)

然后将其注册到相同的文件中,如下所示:

onCreate(){

    registerReceiver(abcd, new IntentFilter("xyz"));
}
Run Code Online (Sandbox Code Playgroud)

在onDestroy中取消注册.

onDestroy(){

   //unRegister
}
Run Code Online (Sandbox Code Playgroud)

现在,每当你想要关闭该Activity时,只需按以下方式调用即可.

sendBroadcast(new Intent("xyz"));
Run Code Online (Sandbox Code Playgroud)

希望这有帮助.

  • 如果服务和活动在同一个应用程序中,我建议使用LocalBroadcastManager.这有几个优点.1-其他应用无法看到广播,您的应用无法从其他应用收到广播.2-您无需在清单中添加接收器.3-它具有更好的性能(请参阅http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html) (2认同)

小智 5

您必须将接收器添加到您的活动的清单中,例如:

    <activity  android:name="MyActivity">
        <intent-filter>
            <action android:name="xyz" />
        </intent-filter>
    </activity>
Run Code Online (Sandbox Code Playgroud)