如何在Android消息应用程序中跟踪发送和接收的消息?

时间:2014-10-20 02:24:14

标签: android sms

我是Android开发的新手(但不是Java),我正在编写自己的Android消息应用程序,希望它可以代替默认的SMS应用程序。我的问题是 - 默认的SMS应用程序如何跟踪发送和接收的消息以及如何完成相同的任务?具体来说,我无法弄清楚如何查找,存储和显示设备用户与其联系人列表成员之间的对话历史记录。我还没有任何初步的代码,因为坦率地说,我不知道从哪里开始。

编辑:尝试设置一个BroadcastReceiver作为第一步(必须从某个地方开始)但是当我通过设备通知时,我正在努力让我的应用程序启动(我正在使用模拟器)。

这是我的BroadcastReceiver类(基于下面的例子)

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;


public class smsBroadcastReceiver extends BroadcastReceiver {
    private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    private static final String TAG = "smsBroadcastReceiver";
    private static final String SMS_SENT = "android.provider.Telephony.SMS_SENT";
    final SmsManager mySMSManager = SmsManager.getDefault();
    String phoneNumber, message;

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(SMS_RECEIVED)) handleIncMessage(intent.getExtras(), context);
        else if (intent.getAction().equals(SMS_SENT)) sendSMS(intent.getExtras(), context);

    }

    void sendSMS(Bundle bundle, Context context){
        phoneNumber = bundle.getString(Intent.EXTRA_PHONE_NUMBER);
        Log.e("info", "Outgoing Number: " + phoneNumber);
        context.sendBroadcast(new Intent("onNewMsgSend"));
    }


    void handleIncMessage(Bundle bundle, Context context) {
        if (bundle != null) {
            Object[] pdus = (Object[]) bundle.get("pdus");
            //database stuff...
            final SmsMessage[] messages = new SmsMessage[pdus.length];
            for (int i = 0; i < pdus.length; i++) {
                String sendingNum = messages[i].getDisplayOriginatingAddress();
                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                String message = messages[i].getDisplayMessageBody();

                Intent msgIntent = new Intent(context, conversationView.class);
                msgIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                        | Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK);

                context.startActivity(msgIntent);

               // Log.i(TAG, "SENDER: " + sendingNum +"; Message: " + message);
                System.out.println("SENDER: " + sendingNum +"; Message: " + message);
            }
            context.sendBroadcast(new Intent("onNewMsg"));
        }
    }
}

我最好的猜测是我在我的活动中做错了什么,但我不确定是什么。我是否需要将我的意图发送到我的主要(启动)活动,然后从那里委派意图,或者我可以将其发送到不是启动器的活动(这是我现在要做的)? / p>

编辑:BroadcastReceiver问题解决了。

1 个答案:

答案 0 :(得分:1)

试试这种方式,希望这可以帮助您解决问题

第1步。

这是你的第一堂课

public class MainActivity extends Activity {

Context context;
Activity act;
ListView lvsms;
public static String msg = "msg", phoneNo = "phoneNo", time = "time";

public static String typeMsg = "0";
public static String typeSend = "1";
// String typeDeliver = "2";

TextView smsno_record;

SimpleCursorAdapter adapter1;

BroadcastReceiver onNewMsg = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
};

BroadcastReceiver onNewMsgSend = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
};

// BroadcastReceiver deliveredreceiver = new BroadcastReceiver() {
// @Override
// public void onReceive(Context context, Intent intent) {
//
// }
// };

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(onNewMsg);
    unregisterReceiver(onNewMsgSend);
    // unregisterReceiver(deliveredreceiver);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    registerReceiver(onNewMsg, new IntentFilter("onNewMsg"));
    registerReceiver(onNewMsgSend, new IntentFilter("onNewMsgSend"));
    // registerReceiver(deliveredreceiver, new IntentFilter(
    // "deliveredreceiver"));
    setContentView(R.layout.complete_sms_data);
    context = MainActivity.this;
    act = MainActivity.this;

    lvsms = (ListView) findViewById(R.id.lvsms);
    smsno_record = (TextView) findViewById(R.id.smsno_record);
    smsdetails(typeMsg);//      sendboxSMS();

}

void smsdetails(String type) {
    Database db = new Database(context);
    // ArrayList<HashMap<String, String>> al = db.getRecord(type);
    LinkedList<HashMap<String, String>> al = db.getRecord(type);
    Log.e("test", "sms al :- " + al.size());
    db.close();
    for (int i = 0; i < al.size(); i++) {
        HashMap<String, String> hm = al.get(i);
        String name = getName(getContentResolver(), hm.get(phoneNo));
        hm.put("name", hm.get(phoneNo) + " " + name);
        Log.e("test", "name :- " + name);
    }
    if (al.size() > 0) {
        lvsms.setVisibility(View.VISIBLE);
        CustomAdapter adapter = null;

        if (type.equals(typeMsg)) {

            Log.e("test", "if condition 1st");

            adapter = new CustomAdapter((Activity) context, al);
            lvsms.setAdapter(adapter);
            // adapter = new SimpleAdapter(context, al,
            // R.layout.list_items_msgs, new String[] { "name", msg,
            // time }, new int[] { R.id.txtPhoneNo,
            // R.id.txtMsg, R.id.txtTime });
        } else if (type.equals(typeSend)) {
            Log.e("test", "if condition 2st");
            adapter = new CustomAdapter((Activity) context, al);
            lvsms.setAdapter(adapter);
            // adapter = new SimpleAdapter(context, al,
            // R.layout.list_items_msgs, new String[] { "name", msg,
            // time }, new int[] { R.id.txtPhoneNo,
            // R.id.txtMsg, R.id.txtTime });
        }
        // else if (type.equals(typeDeliver)) {
        // adapter = new SimpleAdapter(context, al,
        // R.layout.list_items_msgs, new String[] { "name", msg,
        // time }, new int[] { R.id.txtPhoneNo,
        // R.id.txtMsg, R.id.txtTime });
        // }
        lvsms.setAdapter(adapter);
        smsno_record.setVisibility(View.GONE);
    } else {
        Log.e("test", "else condition ");
        lvsms.setAdapter(null);
        lvsms.setVisibility(View.GONE);
    }

}

}

第2步。 这是短信的接收者

public class Receiver extends BroadcastReceiver {

final SmsManager sms = SmsManager.getDefault();
String phoneNumber, message;

public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(
            "android.provider.Telephony.SMS_RECEIVED")) {

        handleIncomingMsg(intent.getExtras(), context);

    } else if (intent.getAction().equals(
            "android.provider.Telephony.SMS_SENT")) {

        sendSMS(intent.getExtras(), context);

    }


}

void handleIncomingMsg(Bundle bundle, Context context) {
    Object[] pdusObj = (Object[]) bundle.get("pdus");
    Database db = new Database(context);
    for (int i = 0; i < pdusObj.length; i++) {
        SmsMessage currentMessage = SmsMessage
                .createFromPdu((byte[]) pdusObj[i]);
        String phoneNumber = currentMessage.getDisplayOriginatingAddress();
        String senderNum = phoneNumber;
        String message = currentMessage.getDisplayMessageBody();

        Intent in1 = new Intent(context, MainActivity.class);
        in1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                | Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(in1);

        Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: "
                + message);
        db.insertRecord(senderNum, message, MainActivity.typeMsg);
    }
    context.sendBroadcast(new Intent("onNewMsg"));
    db.close();
}

void sysAlert(String title, String msg, Context context) {
    AlertDialog alert = new AlertDialog.Builder(context).setTitle(title)
            .setMessage(msg)
            .setNegativeButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).create();
    alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    alert.setCanceledOnTouchOutside(false);
    alert.show();
}

public void onDestroy() {
    telephony.listen(null, PhoneStateListener.LISTEN_NONE);
}

TelephonyManager telephony;

MyPhoneStateListener phoneListener;
boolean ring = false;
boolean callReceived = false;



void handleCalls(Context context) {
    if (phoneListener == null) {
        phoneListener = new MyPhoneStateListener(context);
        telephony = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        telephony.listen(phoneListener,
                PhoneStateListener.LISTEN_CALL_STATE);

    }
}

void sendSMS(Bundle bundle, Context context) {
    phoneNumber = bundle.getString(Intent.EXTRA_PHONE_NUMBER);
    Log.e("info", "Outgoing Number: " + phoneNumber);

    Database db = new Database(context);

    db.insertRecord(phoneNumber, "hii", MainActivity.typeSend);
    //
    // }
    db.close();
    context.sendBroadcast(new Intent("onNewMsgSend"));
}



}

9月3日。  在mainfest中放置权限

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