如何为传入文本创建通知服务?

时间:2013-12-14 05:43:12

标签: android service notifications

我是android的新手..我完全感到困惑的是阅读所有SOQ来解决为传入文本警报创建通知服务的问题。您可以通过解释如何使用特定时间(例如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> 

    

1 个答案:

答案 0 :(得分:0)

您可以使用NotificationManager创建通知。而不是Receiver内的Toast,请使用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);