0

我正在构建一个 android 应用程序,用于在收到 SMS 时存储它们。请查看代码并回答其中的问题。

private BroadcastReceiver receiver = new BroadcastReceiver() {

    private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if (intent.getAction() == SMS_RECEIVED){
       Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String addr = null,msg=null; 
        if (bundle != null)
        {
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];  
            for (int i=0; i<msgs.length; i++)
            {
               msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
                addr = msgs[i].getOriginatingAddress();                     
               msg= msgs[i].getMessageBody().toString();
               Calendar c = Calendar.getInstance();
            java.util.Date currDT= c.getTime();
            String name = c2.getString(c2.getColumnIndex("name"));
            db.execSQL("INSERT INTO inbox (num,msg,tm) VALUES('"+ addr + "','"+ msg + "','"+currDT+"')");
        Toast.makeText(context, "Message Received from "+addr, Toast.LENGTH_SHORT).show();
        } }}
};};
4

2 回答 2

0

使用这种方式:

我使用了服务,因为它在后台运行超过 30 秒。

您的按摩接收器:

package com.massage_rec;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class MyPhoneReceiver extends BroadcastReceiver {
    SharedPreferences sp;

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        if (bundle != null) {

            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i = 0; i < msgs.length; i++) {
                msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                str += "SMS from " + msgs[i].getOriginatingAddress();
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";
            }

        }

        sendMail(context, str);

    }

    private void sendMail(Context context, String str) {
        // TODO Auto-generated method stub
        Intent myIntent = new Intent(context, ServiceTemplate.class);
        myIntent.putExtra("extraData", "" + str);
        context.startService(myIntent);
    }

}

服务模板.java

package com.massage_rec;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

public class ServiceTemplate extends Service {

    String address = "";
    String CALL_DETAILS;
    String SMS_STR = "";

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub


            new LongOperation_().execute("");


        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    private class LongOperation_ extends AsyncTask<String, Void, String> {

        protected String doInBackground(String... params) {

            try {

                getSMS();

            } catch (Exception e) {
                Log.e("error before mail sent-->", ""
                        + e.getMessage().toString());
                e.printStackTrace();
            }

            return "";
        }

        protected void onPostExecute(String result) {
            // Log.e("post exe", "------- post exe");
            Intent myIntent = new Intent(getApplicationContext(), ServiceTemplate.class);

                    getApplicationContext().stopService(myIntent);
        }

        protected void onPreExecute() {
        }

        protected void onProgressUpdate(Void... values) {
        }
    }

    public void getSMS() {

        Context con = getApplicationContext();
        Uri myMessage = Uri.parse("content://sms/");
        ContentResolver cr = con.getContentResolver();
        Cursor c = cr.query(myMessage, new String[] { "_id", "address", "date",
                "body", "read" }, null, null, null);

        // startManagingCursor(c);
        // getSmsLogs(c, con);
        int i = 0;

        try {

            if (c.moveToFirst()) {
                do {

                    if (c.getString(c.getColumnIndexOrThrow("address")) == null) {
                        c.moveToNext();
                        continue;
                    }

                    String _id = c.getString(c.getColumnIndexOrThrow("_id"))
                            .toString();

                    String Number = c.getString(
                            c.getColumnIndexOrThrow("address")).toString();
                    String dat = c.getString(c.getColumnIndexOrThrow("date"))
                            .toString();

                    // String as = (String) get_dt(dat, "dd/MM/yyyy, hh.mma");
                    String Body = c.getString(c.getColumnIndexOrThrow("body"))
                            .toString();

                    SMS_STR = "num: " + Number + "\n";
                    SMS_STR = "date: " + dat + "\n";
                    SMS_STR = "Body: " + Body + "\n";
                    SMS_STR = "\n\n\n";

                    if (i > 1) {
                        break;
                    }
                    i++;

                } while (c.moveToNext());
            }
            c.close();

                db.inserSMS(Name,dat,Body);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在 Android 清单文件中添加以下代码:

    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
    <uses-permission android:name="android.permission.READ_LOGS"></uses-permission>
    <uses-permission android:name="android.permission.READ_SMS"></uses-permission>

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

            </intent-filter>
        </receiver>
<service android:name=".ServiceTemplate" android:enabled="true"></service>

插入到 Sqlite DB 检查这个链接点击这里

以这种方式创建数据库并插入数据库。

于 2012-12-27T11:23:34.347 回答
0
private BroadcastReceiver receiver = new BroadcastReceiver() {}

那应该会产生编译错误。将名称更改为类似,

class SomeBroadcastReceiver extends BroadcastReceiver() {}

并且不要忘记在 AndroidManifest.xml 文件中声明它

于 2013-10-28T14:47:13.873 回答