0

我正在尝试开发一个应用程序,该应用程序允许您在手机到达时将 SMS 的 SQLite 数据库保存在手机上。我正在使用广播接收器来恢复消息,然后将活动组件插入数据库。但是我会用服务替换活动,因为应用程序不会打扰用户。有谁想帮助我。这是我的代码://

MainActivity.java

    public class MainActivity extends BroadcastReceiver {

        private final String ACTION_RECEIVE_SMS = "android.provider.Telephony.SMS_RECEIVED";

        @Override

        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(ACTION_RECEIVE_SMS)) {

                Bundle bundle = intent.getExtras();

                if (bundle != null) {

                    Object[] pdus = (Object[]) bundle.get("pdus");

                    SmsMessage[] message = new SmsMessage[pdus.length];

                    for (int i = 0; i < pdus.length; i++) {

                        message[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    }

                    if (message.length > -1) {

                        String messageBody = message[0].getMessageBody();

                        String phoneNumber = message[0].getDisplayOriginatingAddress();

                        Toast.makeText(context, "Expediteur - numero :" + phoneNumber + " Sms : " + messageBody, Toast.LENGTH_SHORT).show();

                        Intent SecondeItent = new Intent(context, SmsActivity.class);

                        SecondeItent.putExtra("phoneNumber", phoneNumber);

                        SecondeItent.putExtra("messageBody", messageBody);

                        SecondeItent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        context.startActivity(SecondeItent);

                    }
                }
            }
        }
    }

    public class SmsActivity extends Activity {

        smsdao.open();

        smsdao.insertSms(sms);

        Sms smsFromBdd = smsdao.getSmsWithNum(sms.getNum());

        if (smsFromBdd != null) {

            Toast.makeText(this, sms FromBdd.toString(), Toast.LENGTH_LONG).show();
        }

        smsdao.close();
    }
    }

其他文件:SmsDao.java,MyBaseSQLite.java, Sms.java et AndroidManifest.xml,但是这些文件没有问题。

4

1 回答 1

0

示例服务

   public class MainService extends Service {

    public MainService() {
        // TODO Auto-generated constructor stub
    }

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

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

            // your logic

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

}

调用服务

Intent intent = new Intent(this, MainService.class);
    startService(intent);

显现

<service android:name="packageName.MainService" >
    </service>
于 2013-09-09T05:04:52.803 回答