将数据从活动传输到BroadCast Receiver

时间:2017-11-20 09:06:31

标签: android android-intent broadcastreceiver android-notifications

我正在制作一个闹钟应用,当用户输入标题和说明时,它会显示所选时间的通知。 我想在txttitle中存储两个名为txtdescintents的字符串值,并在收到通知时将其发送到broadcast-receiver,该通知的标题和说明应为标题和描述字符串值分别。我已经成功发布了通知,但没有我需要的标题和说明,就像app.support.v7.widget一样 这是我的代码。
AddNote.java

public class AddNote extends AppCompatActivity {

    int mHour, mMin, hour , min, mYear, mMonth, mDay;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_note);
        final CheckBox chckRem = (CheckBox) findViewById(R.id.cHcRem);
        final Button btnOk = (Button) findViewById(R.id.bTok);

        chckRem.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (chckRem.isChecked()){
                    /** It is checked*/
                    // Get Current Date
                  final Calendar c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);


                    DatePickerDialog datePickerDialog = new DatePickerDialog(AddNote.this,
                            new DatePickerDialog.OnDateSetListener() {

                                @Override
                                public void onDateSet(DatePicker view, int year,
                                                      int monthOfYear, int dayOfMonth) {
                               final int day = dayOfMonth;
                               final int yer = year;
                                final int month = monthOfYear;

                                    /** LAUNCH THE TIMEPICKER*/
                                    Calendar c = Calendar.getInstance();
                                    mHour = c.get(Calendar.HOUR_OF_DAY);
                                    mMin =c.get(Calendar.MINUTE);

                                    /** LAUNCH THE TIMEPICKER*/
                                    // Launch Time Picker Dialog
                                    TimePickerDialog timePickerDialog = new TimePickerDialog(AddNote.this,
                                            new TimePickerDialog.OnTimeSetListener() {

                                                @Override
                                                public void onTimeSet(TimePicker view, int hourOfDay,
                                                                      int minute) {
                                                    /**tHIS*/
                                                    hour = hourOfDay;
                                                    min = minute;
                                                    int sec = 0;
                                                    Calendar cl = Calendar.getInstance();
                                                    cl.setTimeInMillis(System.currentTimeMillis());
                                                    cl.clear();
                                                    cl.set(yer, month, day, hour, min);
                                                    EditText txtitle = (EditText) findViewById(R.id.tTit);
                                                    EditText txtdesc = (EditText) findViewById(R.id.tDet);
                                                    Intent notMessage = new Intent(getApplicationContext(), NotificatioRec.class);
                                                    notMessage.putExtra("TITLE", txtitle.toString().trim());
                                                    notMessage.putExtra("DEC", txtdesc.toString().trim());
                                                    PendingIntent pi = PendingIntent.getBroadcast(AddNote.this, 0, notMessage, PendingIntent.FLAG_UPDATE_CURRENT);
                                                    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                                                    am.set(AlarmManager.RTC_WAKEUP, cl.getTimeInMillis(), pi);
                                                    Toast.makeText(AddNote.this, "Reminder Added", Toast.LENGTH_SHORT).show();
                                                }
                                            }, mHour, mMin, false);
                                    timePickerDialog.show();

                                }
                            }, mYear, mMonth, mDay);
                    datePickerDialog.show();

                }

            }
        });

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    TextoDatabaseHelper textoDatabaseHelper = new TextoDatabaseHelper(AddNote.this);
                    SQLiteDatabase db = textoDatabaseHelper.getReadableDatabase();
                    Calendar calend = Calendar.getInstance();
                    int YEAR = calend.get(Calendar.YEAR);
                    int MONTH = calend.get(Calendar.MONTH);
                    int DAY = calend.get(Calendar.DAY_OF_MONTH);
                    String date = DAY + "-" + MONTH + "-" + YEAR;
                    EditText txt_title = (EditText) findViewById(R.id.tTit);
                    String Title = txt_title.getText().toString().trim();
                    EditText txt_Desc = (EditText) findViewById(R.id.tDet);
                    String Desc = txt_Desc.getText().toString().trim();
                    insertNote(db, Title, Desc, date);
                    Toast.makeText(AddNote.this, "Note Added" , Toast.LENGTH_SHORT).show();
                    AddNote.this.finish();
                }catch (SQLException e){
                    Toast.makeText(AddNote.this, "Can't add a new note! Try again.", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    public static void insertNote(SQLiteDatabase db, String title, String desc, String date){
        ContentValues Notes = new ContentValues();
        Notes.put("TITLE", title);
        Notes.put("DESCRIPTION", desc);
        Notes.put("DATE", date);
        db.insert("NOTES", null, Notes);
    }
}

NotificatioRec.java

public class NotificatioRec extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String title = intent.getStringExtra("TITLE");
        String desc  = intent.getStringExtra("DESC");
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0 , new Intent(context, MainActivity.class), 0);
        NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.logo)
                .setContentTitle(title).setContentText(desc);
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setCategory(Notification.CATEGORY_ALARM);
        mBuilder.setAutoCancel(true);

        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());
    }
}

然而,唯一的问题是它没有显示标题和描述。

2 个答案:

答案 0 :(得分:0)

使用如下所示 广播发送到活动

 Intent smsIntent = new Intent("otp");
            smsIntent.putExtra("message",sms_str);

            LocalBroadcastManager.getInstance(context).sendBroadcast(smsIntent);

让活动接收上述意图。

 private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase("otp")) {



            }
        }
    };

答案 1 :(得分:0)

在您的广告活动中添加以下代码,从

发送意图
Intent intent = new Intent("my.action.data");
intent.putExtra("otp", otp);
sendBroadcast(intent);

获取数据接收方法

public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
   Log.i("onReceive Method", "" + action);

   if(action.equals("my.action.data")){
          String otp= intent.getExtras().getString("otp");

   }
 }

在接收器(Manifest File)中添加以下代码

<receiver android:name=".SmsReceiver" android:enabled="true">
     <intent-filter>
     <action android:name="android.provider.Telephony.SMS_RECEIVED" />
     <action android:name="my.action.data" />
 </intent-filter>
</receiver>