2013-12-14 34 views
1

我是Android的新手..我完全困惑,閱讀所有SOQs來解決傳入文本警報通知服務的問題。可以通過解釋如何創建後臺服務的具體步驟(例如5分鐘)以及該服務用於通知用戶傳入文本的步驟來幫助我。 非常感謝。如何爲傳入文本創建通知服務?

import android.content.BroadcastReceiver; 

    import android.content.Context; 
    import android.content.Intent; 
    import android.os.Bundle; 
    import android.telephony.SmsMessage; 
    import android.widget.Toast; 

    public class SMSReceiver extends BroadcastReceiver { 
public void onReceive(Context context, Intent intent) { 
    Bundle myBundle = intent.getExtras(); 
    SmsMessage[] messages = null; 
    String strMessage = ""; 

    if (myBundle != null) { 
     Object[] pdus = (Object[]) myBundle.get("pdus"); 
     messages = new SmsMessage[pdus.length]; 

     for (int i = 0; i < messages.length; i++) { 
      messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); 
      strMessage += "SMS From: " 
        + messages[i].getOriginatingAddress(); 
      strMessage += " : "; 
      strMessage += messages[i].getMessageBody(); 
      strMessage += "\n"; 
     } 

     Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show(); 
    } 
    } 
} 

,並在清單文件我寫的,

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

+0

我用BrodcasRreciever類來獲取短信提醒是一種正確的方法嗎? – user3057567

+0

然後顯示你的代碼,我們不需要從頭開始工作。展示你在排隊時做了什麼,這樣讀者就可以知道什麼是錯的,以及你卡在哪裏。 – SilentKiller

+0

我已在清單文件中添加了相關代碼的權限和,但在收到傳入消息後仍然無法看到輸出....我該怎麼辦? – user3057567

回答

0

可以使用NotificationManager創建通知。而不是你的Receiver裏面的吐司,使用Notification。請參閱下面的示例代碼。

NotificationManager notificationManager1= (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

Intent i=new Intent(context,TragetActivity.class);// TargetActivity is opened when you click on the notification. 
PendingIntent pi=PendingIntent.getActivity(context, 0, i, 0); 

// Build notification 
// Actions are just fake 
Notification noti2=new Notification(R.drawable.icon2, "New SMS from " + "Nizam", System.currentTimeMillis()); 
noti2.setLatestEventInfo(context, "SMS", "Hii", pi); 
noti2.flags = Notification.FLAG_AUTO_CANCEL; 
//Show notification 
notificationManager1.notify(1, noti2);