似乎SMS上的广播接收器没有发射

时间:2014-01-23 00:47:23

标签: android sms broadcastreceiver

配方:本书(http://www.informit.com/articles/article.aspx?p=2111971&seqNum=2)中的“根据收到的短信自动发送短信”对我不起作用,

在模拟器上它工作正常,但在真实设备上没有。为什么? 我使用的是HTC Legend和android 2.3.7(cyanogenmod)。 谢谢你的帮助。

在以下几行中,我将提供有关我的申请的更多详细信息。

1)ResponderService:负责监听传入消息的服务。

package tn.a2soft.a2soft_crm;

import java.util.ArrayList;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class ResponderService extends Service {

    // The Action fired by the Android-System when a SMS was received.
    private static final String RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
    private static final String SENT_ACTION = "SENT_SMS";
    private static final String DELIVERED_ACTION = "DELIVERED_SMS";
    String requester;
    String reply = "";


    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        IntentFilter filter = new IntentFilter(RECEIVED_ACTION);
        filter.setPriority(500);
        registerReceiver(SMSreceiver, filter);

        registerReceiver(sentReceiver, new IntentFilter(SENT_ACTION));

        registerReceiver(deliverReceiver, new IntentFilter(DELIVERED_ACTION));

        //registerReceiver(sender, new IntentFilter(SENT_ACTION));
    }

//  private BroadcastReceiver sender = new BroadcastReceiver() {
//
//      @Override
//      public void onReceive(Context c, Intent i) {
//          if (i.getAction().equals(SENT_ACTION)) {
//              if (getResultCode() != Activity.RESULT_OK) {
//                  String reciptent = i.getStringExtra("recipient");
//                  requestReceived(reciptent);
//              }
//          }
//      }
//  };
    private BroadcastReceiver sentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent in) {
            switch (getResultCode()) {
            case Activity.RESULT_OK:
                // sent SMS message successfully;
                smsSent();
                break;
            default:
                // sent SMS message failed
                smsFailed();
                break;
            }
        }
    };

    private BroadcastReceiver SMSreceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent in) {

            // TODO Auto-generated method stub
            Log.v("ResponderService", "On Receive");
            Toast.makeText(c, "Revceive SMS",Toast.LENGTH_LONG).show();
            if (in.getAction().equals(RECEIVED_ACTION)) {
                Log.v("ResponderService", "On SMS RECEIVE");
                Bundle bundle = in.getExtras();
                if (bundle != null) {

                    Object[] pdus = (Object[]) bundle.get("pdus");
                    SmsMessage[] messages = new SmsMessage[pdus.length];

                    for (int i = 0; i < pdus.length; i++) {
                        Log.v("ResponderService", "FOUNDMESSAGE");
                        messages[i] = SmsMessage
                                .createFromPdu((byte[]) pdus[i]);
                    }

                    for (SmsMessage message : messages) {
                        requestReceived(message.getOriginatingAddress());
                    }

                    respond();

                }

            }
        }
    };


    public void smsSent() {
        Toast.makeText(this, "SMS sent", Toast.LENGTH_SHORT).show();
    }

    public void smsFailed() {
        Toast.makeText(this, "SMS sent failed", Toast.LENGTH_SHORT).show();
    }

    public void smsDelivered() {
        Toast.makeText(this, "SMS delivered", Toast.LENGTH_SHORT).show();
    }

    public void requestReceived(String f) {
        Log.v("ResponderService", "In requestReceived");
        requester = f;
    }

    BroadcastReceiver deliverReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent in) {
            // SMS delivered actions
            smsDelivered();
        }
    };



    public void respond() {
        Log.v("ResponderService", "Responing to " + requester);

        reply = "Thank you for your message. I am busy now. "
                + "I will call you later";
        SmsManager sms = SmsManager.getDefault();

        Intent sentIn = new Intent(SENT_ACTION);
//      Intent sentIn = new Intent("android.telephony.SmsManager.STATUS_ON_ICC_SENT");
        PendingIntent sentPIn = PendingIntent.getBroadcast(this, 0, sentIn, 0);

        Intent deliverIn = new Intent(DELIVERED_ACTION);
        PendingIntent deliverPIn = PendingIntent.getBroadcast(this, 0,
                deliverIn, 0);

        ArrayList<String> Msgs = sms.divideMessage(reply);
        ArrayList<PendingIntent> sentIns = new ArrayList<PendingIntent>();
        ArrayList<PendingIntent> deliverIns = new ArrayList<PendingIntent>();
        for (int i = 0; i < Msgs.size(); i++) {
            sentIns.add(sentPIn);
            deliverIns.add(deliverPIn);
        }

        sms.sendMultipartTextMessage(requester, null, Msgs, sentIns, deliverIns);
        // sms.sendTextMessage(requester, null, reply, sentPIn, deliverPIn);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(SMSreceiver);
        unregisterReceiver(deliverReceiver);
        unregisterReceiver(sentReceiver);
//      unregisterReceiver(sender);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

}

2)包含一个按钮的唯一和主要活动,通过点击它我启动服务:

package tn.a2soft.a2soft_crm;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    Button startService;
    ComponentName cn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService = (Button) this.findViewById(R.id.startservice);
        startService.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    // start Service
                    Intent svc = new Intent(MainActivity.this,
                            ResponderService.class);
                    cn = (ComponentName)startService(svc);
                    Toast.makeText(MainActivity.this, cn.getClassName(),
                            Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Log.e("onCreate", "service creation problem", e);
                    Toast.makeText(MainActivity.this,
                            "service creation problem", Toast.LENGTH_LONG)
                            .show();
                }
//              Intent in = new Intent(MainActivity.this, SMSResponder.class);
//              startActivity(in);
            }
        });

    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();

    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //stopService(new Intent(MainActivity.this,ResponderService.class));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

3)清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tn.a2soft.a2soft_crm"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppBaseTheme" >
        <activity
            android:name="tn.a2soft.a2soft_crm.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="tn.a2soft.a2soft_crm.SMSResponder"
            android:label="@string/app_name" >
        </activity>

<!--         <receiver
            android:name=".SMSReceiver"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.BROADCAST_SMS" >
            <intent-filter android:priority="999" >
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver> -->

        <service
            android:name=".ResponderService"
            android:enabled="true" >
        </service>
    </application>

</manifest>

正如我在模拟器上的示例工作之前告诉过你的那样但不是在真实设备上。 谢谢你的帮助,我真的很头疼。

3 个答案:

答案 0 :(得分:0)

该部分需要在清单文件中取消注释。我还建议将其简化为:

<receiver android:name=".SMSReceiver" android:enabled="true">
<intent-filter android:priority="999" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

答案 1 :(得分:0)

stackoverflow论坛是程序员的天堂,我找到了解决方案并且我已经测试了它,并且在这个论坛中link(将broadcastreceiver的优先级设置为Integer.MAX_VALUE)对我来说很好。感谢您的帮助,特别是那些试图帮助我的“PVS”。

答案 2 :(得分:0)

你可以像地下知识库所暗示的那样将优先级值增加到MAX_INT,但这并不会真正做到这一点 - 这些天似乎每个人都这样做!如果你想要更好的控制,尽管其他应用程序,我建议还实现一个监听器。

// Register to detect incoming SMS
incomingSmsHandler = new Handler();
contentResolver.registerContentObserver(smsUri, true, new ContentObserver(incomingSmsHandler)
{
// Etc
}