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

后端 未结 1 568
野性不改
野性不改 2020-12-18 14:48

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.

相关标签:
1条回答
  • 2020-12-18 15:28

    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);
    
    0 讨论(0)
提交回复
热议问题