Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
790 views
in Technique[技术] by (71.8m points)

android - What is the simplest way to send message from local service to activity

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.

In my Activity:

@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);

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

My working example now is:

Activity:

        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);

Manifest:

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

Service:

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...