在后台启动应用程序 - 后台启动服务将sms内容复制到db

时间:2013-09-09 04:46:51

标签: java android sqlite android-intent

我正在尝试开发一个应用程序,允许您在手机到达时保存手机短信的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和AndroidManifest.xml,但这些文件没有问题。

1 个答案:

答案 0 :(得分: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>