来自Service,调用Activity方法(如果它在前台)

时间:2018-01-05 10:25:37

标签: android android-activity service foreground

从Android 服务,我想调用活动方法,但前提是活动位于前景

如果活动不在前台,我不希望发生任何事情。

实现这一目标的最简单方法是什么?

3 个答案:

答案 0 :(得分:3)

服务总是更好地广播事件如果活动正在收听该广播将响应。如果活动没有收听,那么什么都不会发生,它会忽略。

这是比您提出的解决方案更好的解决方案。

答案 1 :(得分:2)

我找到了一个非常简单的解决方案,改编自this previous answer

在服务上

Intent intent = new Intent(MainActivity.RECEIVER_INTENT);
intent.putExtra(MainActivity.RECEIVER_MESSAGE, myMessage);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

关于活动

public static final String RECEIVER_INTENT = "RECEIVER_INTENT";
public static final String RECEIVER_MESSAGE = "RECEIVER_MESSAGE";

onCreate()上创建一个监听器:

public void onCreate(Bundle savedInstanceState) {
    ...
    mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra(RECEIVER_MESSAGE);
            // call any method you want here
        }
    };
}

onStart()注册:

@Override
protected void onStart() {
    super.onStart();
    LocalBroadcastManager.getInstance(this).registerReceiver((mBroadcastReceiver), 
        new IntentFilter(RECEIVER_INTENT)
    );
}

onStop()中取消注册:

@Override
protected void onStop() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
    super.onStop();
}

答案 2 :(得分:0)

您只需使用Interface来检查活动是在后台还是在前台。

我正在分享一些代码以便有所了解。

public interface CheckAppInForeground {

boolean isAppInForGround();
}

在您的活动中

public class MainActivity extends AppCompatActivity implements CheckAppInForeground {

 Boolean isAppInForeGround;

  @Override
protected void onResume() {
    super.onResume();
    isAppInForeGround = true;
}

@Override
protected void onStop() {
    super.onStop();
    isAppInForeGround = false;
}

@Override
public boolean isAppInForGround() {
    return isAppInForeGround;
}
}

您的服务类

public class MyService extends Service {
Activity activity;

public MyService(Activity activity) {
    this.activity = activity;
}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    MainActivity mainActivity = (MainActivity) activity;
    if (activity != null) {
        boolean isActivityInForGround = mainActivity.isAppInForGround();
        if (isActivityInForGround) {
            // Do what you want to do when activity is in foreground
        } else {
            // Activity is in background
        }
    } else {
        // Activity is destroyed
    }
    return super.onStartCommand(intent, flags, startId);
}
}

我想我对代码很清楚。如果您发现遗漏或不清楚的地方,请告诉我