来自broadcastReceiver的服务调用功能

时间:2012-11-10 23:27:01

标签: android service sms broadcastreceiver

我一直在努力解决这个问题。 我有一个广播接收器,假设接收短信'并且它这样做,但我想在我的服务中使用方法/功能,目的是最终使它成为前台服务,永远不会关闭。 Broadcastreceiver看起来像这样:

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 
        }                         
    }
}

在接收的清单中我添加了:

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

1 个答案:

答案 0 :(得分:3)

Intent myIntent = new Intent(context, SmsService.class);
myIntent.putExtra("msg", msgs);
context.startService(myIntent);