什么是本地服务活动发送信息的最简单方法最简单、方法、信息

2023-09-04 10:25:17 作者:浅唱、若相爱

我是听着电话的服务。当手机进入闲置状态,我想将消息发送到我的活动。它看起来像我有两个选择,以实现这一目标。 BroadcastReceiver的和有约束力的服务。 BroadcastReceiver的看起来像一个简单的机制,所以我尝试了下面的测试。

I have a service which is listening to the phone. When the phone goes IDLE, I want to send a message to my Activity. It looks like I have two options to accomplish this. BroadcastReceiver and binding to the Service. BroadcastReceiver looked like an easier mechanism, so I tried the following test.

在我的活动:

@Override
protected void onStart() {
    super.onStart();
    IntentFilter filter = new IntentFilter("MyAction");
    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "Yay.......");
            abortBroadcast();
        }
    }, filter);
}

在我的服务,这是监听事件,当我发现我想要的事件:

In my Service which is listening for events, when I detect my desired event:

    Intent localIntent = new Intent(_context, MainActivity.class);
    intent.setAction("MyAction");
    _context.sendOrderedBroadcast(localIntent, null);

在我的测试中,的onReceive()方法不会被调用后,我曾经看过发送与调试器的广播。我在想什么?此外,是一个BroadcastReceiver为本地服务与活动通信的最简单的方法?

In my test, the onReceive() method is never called after I have watched the broadcast being sent with the debugger. What am I missing? Also, is a BroadcastReceiver the simplest way for a local service to communicate with an Activity?

推荐答案

我觉得我在我最初的测试案例的一些问题。 1.当我在我的服务创建了我的意图,应采取行动作为参数。 2.我认为我需要的意图过滤器添加到我的清单。

I think I had a few problems in my initial test case. 1. When I created my Intent in my service, it should take the "action" as the argument. 2. I believe that I needed to add the intent filter to my manifest.

我的工作比如现在是:

活动:

        startService(intent);

        IntentFilter filter = new IntentFilter(PhoneListeningService.PHONE_IDLE);
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(TAG, "Yay.......");
            }
        }, filter);

清单:

    <activity android:name=".MainActivity" android:screenOrientation="portrait" >
       <intent-filter>
            <action android:name="com.ncc.PhoneListeningService.action.PHONE_IDLE" />
        </intent-filter>
    </activity>

服务:

声明的公共常量命名为行动和广播的意图。

Declare public constant for the named "action" and broadcast an intent.

public static final String PHONE_IDLE = "com.ncc.PhoneListeningService.action.PHONE_IDLE";

...我的侦听器检测手机空闲:

... my listener detects phone idle:

            Intent intent = new Intent(PHONE_IDLE);
            sendBroadcast(intent);