Android小项目,短信弹窗提示+回复

最近没事干,写写自己要用的东西,
之前用miui的时候就很喜欢那个短信提示框,回短信方便,
自从用回原生后就一直没这功能,又不喜欢go短信那东西,太太太臃肿,而且我喜欢原生的Holo风格,
那就自己动手写一个吧~

代码也很简单的,注册个BroastcastReceiver接收短信广播,接收到广播后获取短信内容通过intent把内容传并且跳转到一个theme是Dialog的activity,然后activity把短信内容显示出来就完事了~

DialogActivity.java

View Code
package com.masaila.smsdialog;

import java.util.List;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class DialogActivity extends Activity implements OnClickListener {

    private TextView textView_sender, textView_number, textView_time, textView_content;
    private ImageButton imageButton_cencel, imageButton_send;
    private EditText editText_content;
    private Bundle bundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_dialog);
        init();

    }

    private void init() {
        textView_sender = (TextView) findViewById(R.id.textView_sender);
        textView_number = (TextView) findViewById(R.id.textView_number);
        textView_time = (TextView) findViewById(R.id.textView_time);
        textView_content = (TextView) findViewById(R.id.textView_content);
        imageButton_cencel = (ImageButton) findViewById(R.id.imagebutton_cancel);
        imageButton_send = (ImageButton) findViewById(R.id.imagebutton_send);
        editText_content = (EditText) findViewById(R.id.edittext_content);
        bundle = getIntent().getExtras();
        textView_sender.setText(bundle.getString("sender"));
        textView_number.setText(bundle.getString("number"));
        textView_time.setText(bundle.getString("time"));
        textView_content.setText(bundle.getString("content"));
        imageButton_cencel.setOnClickListener(this);
        imageButton_send.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.imagebutton_cancel:
                DialogActivity.this.finish();
                break;
            case R.id.imagebutton_send:
                sendSms(editText_content.getText().toString(), bundle.getString("number"));
                System.err.println(editText_content.getText().toString()+bundle.getString("number"));
                DialogActivity.this.finish();
                break;
        }
    }

    
    /*
     * 发短信
     */
    private void sendSms(String content, String phoneNumber) {
        SmsManager sms = SmsManager.getDefault();
        PendingIntent sentintent = PendingIntent.getBroadcast(DialogActivity.this, 0, new Intent(), 0);
        try {
            if (content.length() > 70) {
                List<String> msgs = sms.divideMessage(content);
                for (String msg : msgs) {
                    sms.sendTextMessage(phoneNumber, null, msg, sentintent, null);
                }
            }
            else {
                sms.sendTextMessage(phoneNumber, null, content, sentintent, null);
            }
        }
        catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}

SmsBroadcastReceiver.java

View Code
package com.masaila.smsdialog;

import java.sql.Date;
import java.text.SimpleDateFormat;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsMessage;

public class SmsBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Bundle bundle = intent.getExtras();
        Object messages[] = (Object[]) bundle.get("pdus");
        SmsMessage smsMessage[] = new SmsMessage[messages.length];
        String number="", content="", sendtime="", sender="";
        Date date;
        for (int n = 0; n < messages.length; n++) {
            smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
            number = smsMessage[n].getOriginatingAddress();// 获取短信的发送者
            content += smsMessage[n].getMessageBody();// 获取短信的内容
            date = new Date(smsMessage[n].getTimestampMillis());// 获取短信的接收时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sendtime = format.format(date);
            sender = getContactNameFromPhoneNum(context, number);
            System.err.println(content);

        }
        intent.putExtra("sender", sender);
        intent.putExtra("number", number);
        intent.putExtra("content", content);
        intent.putExtra("time", sendtime);
        // 这样启动一个Activity一定要把Intent打上FLAG_ACTIVITY_NEW_TASK的标志,不然会报错
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(context, DialogActivity.class);
        context.startActivity(intent);

        if (MySharedPreference.getBoolean(context, "com.masaila.smsdialog_preferences", "CloseOtherSms")) {
            this.abortBroadcast();
        }
    }

    /**
     * 通过电话号码获取姓名
     */
    public String getContactNameFromPhoneNum(Context context, String phoneNum) {
        String contactName = "";

        // 处理电话号码格式问题
        if (phoneNum.length() > 11) {
            ContentResolver cr = context.getContentResolver();
            Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?", new String[] { phoneNum }, null);
            if (pCur.moveToFirst()) {
                contactName = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                pCur.close();
            }
            if (contactName.equals("")) {
                phoneNum = phoneNum.substring(phoneNum.length() - 11);
                System.out.println(phoneNum);
            }
        }

        ContentResolver cr = context.getContentResolver();
        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?", new String[] { phoneNum }, null);
        if (pCur.moveToFirst()) {
            contactName = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            pCur.close();
        }

        if (contactName == "") {
            contactName = phoneNum;
        }
        return contactName;
    }
}

activity_dialog.xml

View Code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff1f1f1"
    android:orientation="vertical" >

    <!-- Title start -->    
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#222222" >

        <TextView
            android:id="@+id/textView_sender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="8.0dip"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/textView_number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView_sender"
            android:layout_below="@+id/textView_sender" />

        <TextView
            android:id="@+id/textView_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/textView_sender"
            android:layout_marginLeft="15.0dip"
            android:layout_toRightOf="@+id/textView_number" />

        <LinearLayout
            android:layout_width="48.0dip"
            android:layout_height="48.0dip"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageButton
                android:id="@+id/imagebutton_cancel"
                android:layout_width="fill_parent"
                android:layout_height="0.0dip"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1.0"
                android:background="@drawable/imagebutton"
                android:src="@drawable/ic_menu_close_clear_cancel" />
        </LinearLayout>
    </RelativeLayout>
    <!-- Title end -->
    
    <!-- SMS content start -->  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8.0dip"
        android:layout_marginTop="8.0dip"
        android:background="@color/list_background"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8.0dip"
            android:layout_marginRight="8.0dip"
            android:autoLink="all"
            android:textColor="@android:color/black"
            android:textSize="16.0sp" />
    </LinearLayout>
    <!-- SMS content start -->
    
    <View
        android:layout_width="fill_parent"
        android:layout_height="0.9dip"
        android:background="#d8d8d8" />

    <!-- Send start -->    
    <LinearLayout
        android:id="@+id/bottom_panel"
        android:layout_width="fill_parent"
        android:layout_height="54.0dip"
        android:background="#ffffffff"
        android:orientation="horizontal"
        android:paddingBottom="4.0dip" >

        <EditText
            android:id="@+id/edittext_content"
            android:layout_width="0.0dip"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginLeft="8.0dip"
            android:layout_weight="1.0"
            android:autoText="true"
            android:capitalize="sentences"
            android:hint="输入信息"
            android:imeOptions="actionSend|flagNoEnterAction"
            android:inputType="textCapSentences|textAutoCorrect|textMultiLine|textShortMessage"
            android:maxLines="3"
            android:minHeight="48.0dip"
            android:textColor="@android:color/black"
            android:textSize="16.0sp" />

        <LinearLayout
            android:id="@+id/button_with_counter"
            android:layout_width="48.0dip"
            android:layout_height="48.0dip"
            android:layout_gravity="bottom"
            android:orientation="vertical" >

            <ImageButton
                android:id="@+id/imagebutton_send"
                style="\?android:attr/borderlessButtonStyle"
                android:layout_width="fill_parent"
                android:layout_height="0.0dip"
                android:layout_weight="1.0"
                android:background="@drawable/imagebutton"
                android:nextFocusLeft="@id/edittext_content"
                android:src="@drawable/ic_send_holo_light" />
        </LinearLayout>
    </LinearLayout>   
    <!-- Send end -->

</LinearLayout>

 

 源码~~

http://url.cn/06OZio

 

 

posted on 2012-08-08 17:13  MASAILA  阅读(564)  评论(0)    收藏  举报

导航