如果从非应用Android接收短信,则不会调用GCMBroadcastreceiver

时间:2015-08-30 13:09:21

标签: android broadcastreceiver google-cloud-messaging intentservice

我制作的android应用程序可以短信并拨打应用程序和非应用程序(GSM或其他电话号码)。如果我从应用程序发送短信到应用程序,GCMBroadcastreceiver被调用,但如果我从GSM发送短信到我的应用程序,GCMBroadcastreceiver未调用,这是我的代码:

GCMBroadcastreceiver.java:

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    private static final String TAG = GcmBroadcastReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "receive wakeful broadcast");
        ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        //setResultCode(Activity.RESULT_OK);
    }

}

GcmIntentService.java:

public class GcmIntentService extends IntentService {

    private static final String TAG = GcmIntentService.class.getSimpleName();
    private static final int NOTIFICATION_ID = 2;

    private long[] vibratePattern = {
            0, 500, 500, 500
    };

    private NotificationManager notificationManager;
    private AddressBookManager addressBookManager;

    public GcmIntentService() {
        super(TAG);
        addressBookManager = AddressBookManager.getInstance();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

        Intent messageIntent = new Intent(this, GetMessageService.class);
        startService(messageIntent);

        String messageType = gcm.getMessageType(intent);
        Log.d(TAG, "messageType: " + messageType);
        if(!extras.isEmpty()){
            Log.d(TAG, "2.extras: " + extras);
            if(GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)){

            }

            if(GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)){

            }

            if(GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)){
                String extrasMessage = extras.getString("message");
                Log.d(TAG, "message: " + extrasMessage);

                if (extrasMessage!=null){
                    try {
                        JSONArray arrayJson = new JSONArray(extrasMessage);
                        if (arrayJson!=null){
                            for(int i = 0; i < arrayJson.length(); i++){
                                JSONObject json = arrayJson.getJSONObject(i);
                                String type = json.getString("type");
                                String from = json.getString("from");
                                String message = json.getString("message");
                                sendNotification(type, from, message);
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                else {
                    //Google Cloud Messaging Data is null
                    //sendNotification(null, null, null);
                }

            }
        }       

        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    private void sendNotification(String type, String msisdn, String message){
        String title = msisdn;
        notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_message_man);

        if(addressBookManager.hasUser(msisdn)){
            User user = addressBookManager.getUser(msisdn);

            if(!StringUtil.isEmpty(user.getContact().displayName)){
                title = user.getContact().displayName;
            }

            if(!StringUtil.isEmpty(user.getContact().photoThumbUri)){
                try {
                    bitmap = Media.getBitmap(getContentResolver(), Uri.parse(user.getContact().photoThumbUri));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(!StringUtil.isEmpty(user.getAvatarFile())){
                Bitmap fileBitmap = ImageTools.readFromFile(user.getAvatarFile());
                if(fileBitmap != null){
                    bitmap = fileBitmap;
                }
            }
        }

        if("multi_sender".equals(type)){
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_message_multi);                                 
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_notif)
        .setLargeIcon(bitmap)
        .setContentTitle(title)
        .setVibrate(vibratePattern)
        .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
        .setAutoCancel(true)
        .setContentText(message);       

        Intent resultIntent = new Intent(this, ConversationActivity.class);
        char c = msisdn.charAt(0);
        if (msisdn.startsWith("+") || (c >= 'A' && c <= 'Z')|| (c >= 'a' && c <= 'z') || msisdn.startsWith("0")) {
            resultIntent.putExtra("msisdn", msisdn);
        }
        else {
            //Tambah + di depan msisdn agar sama dengan msisdn di MessageActivity (History Message bisa dipanggil)
            String msisdns = "+"+msisdn;
            resultIntent.putExtra("msisdn", msisdns);
        }

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);

        notificationManager.notify(NOTIFICATION_ID, builder.build());       
    }
}

清单:

<!-- receivers -->
        <receiver
            android:name=".gcm.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.marlinmedia.tkitalk" />
            </intent-filter>
        </receiver>

        <!-- services -->
        <service android:name=".gcm.GcmIntentService" />

我的代码还是其他什么问题?

1 个答案:

答案 0 :(得分:0)

您可以直接从您的应用发送短信到其他应用,而无需使用GCM。 GCM的体系结构用于通过GCM服务器在Internet上发送推送通知。

您可以使用 短信管理员 和以下权限将短信从一个应用发送到另一个应用。

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

有关详细信息,请查看此tutorial