【问题标题】:How make Activity run to service如何让 Activity 运行到服务
【发布时间】:2017-06-07 12:32:40
【问题描述】:

我是 java 新手,想知道如何在后台运行活动和服务。因此,当活动关闭并重新打开时,它会与服务一起继续。不知道怎么解释。

假设有 3 个服务,每个服务每小时执行一次。

服务 1... 1 小时 ... 服务 2 ... 1 小时 ... 服务 3. 完成。

并且每次执行时都会在活动中设置一个可见的文本视图。但是,当活动关闭时,不会创建文本视图。

我发现的唯一方法是使用变量,如下例所示

服务 1:

public int service_one_done = 1;

服务 2:

public int service_two_done = 1;

服务 3:

public int service_three_done = 1;

创建活动:

if (service_one_done == 1) { textview_example1.setVisibility(View.VISIBLE)
} if (service_two_done == 1) { textview_example2.setVisibility(View.VISIBLE)
} if (service_three_done == 1) { textview_example3.setVisibility(View.VISIBLE)
}

我想知道是否有更好的方法来做到这一点

【问题讨论】:

  • 有很多更好的方法;尝试使用广播接收器,这样当 Activity 运行时,它会监听服务发送的广播并更新文本视图,当你的 Activity 被销毁时,它不会监听这些广播。希望这会有所帮助

标签: java android android-activity service


【解决方案1】:

在我的服务类中我写了这个

private static void sendMessageToActivity(Location l, String msg) {
    Intent intent = new Intent("GPSLocationUpdates");
    // You can also include some extra data.
    intent.putExtra("Status", msg);
    Bundle b = new Bundle();
    b.putParcelable("Location", l);
    intent.putExtra("Location", b);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

在活动端,我们必须接收这个广播消息

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
            mMessageReceiver, new IntentFilter("GPSLocationUpdates"));

通过这种方式,您可以向 Activity 发送消息。这里 mMessageReceiver 是该类中的类,您将执行您想要的任何操作....

在我的代码中我这样做了......

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String message = intent.getStringExtra("Status");
        Bundle b = intent.getBundleExtra("Location");
        lastKnownLoc = (Location) b.getParcelable("Location");
        if (lastKnownLoc != null) {
            tvLatitude.setText(String.valueOf(lastKnownLoc.getLatitude()));
            tvLongitude
                    .setText(String.valueOf(lastKnownLoc.getLongitude()));
            tvAccuracy.setText(String.valueOf(lastKnownLoc.getAccuracy()));
            tvTimestamp.setText((new Date(lastKnownLoc.getTime())
                    .toString()));
            tvProvider.setText(lastKnownLoc.getProvider());
        }
        tvStatus.setText(message);
        // Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }
};

参考here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    相关资源
    最近更新 更多