简体   繁体   English

来自广播接收器的服务中的呼叫功能

[英]Call function in service from broadcastReceiver

I have been struggling with the problem. 我一直在努力解决这个问题。 I have a Broadcast receiver that is suppose to receive SMS' and it does that, but I want to use a method/function in my Service, the intent is to make it a foreground service eventually, that never shuts down. 我有一个广播接收器,该接收器应该接收SMS',并且它确实做到了,但是我想在Service中使用一种方法/功能,目的是最终使其成为前台服务,并且永远不会关闭。 The Broadcastreceiver looks like this: 广播接收器如下所示:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;            
        if (bundle != null)
        {
        //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
            }
        //want to send msgs[] to SmsService 
        }                         
    }
}

In the manifest for making it receive I have added: 在要接收的清单中,我添加了:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.BROADCAST_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS" />
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".SmsReceiver" > 
        <intent-filter> 
            <action android:name= "android.provider.Telephony.SMS_RECEIVED" /> 
        </intent-filter> 
    </receiver>
    <service android:name="SmsService"></service>
</application>
Intent myIntent = new Intent(context, SmsService.class);
myIntent.putExtra("msg", msgs);
context.startService(myIntent);   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM