我正在应用程序中构建通知服务,为此,我创建了一个布局,该布局允许用户输入日期(通过日期选择器)和时间(通过时间选择器),并且值将显示在TextViews中。我有两个类,一个是主类(用于实现布局)

另一个是BroadcastManager类,

public class BroadcastManager extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    try {
        String yourDate //must define
        String yourHour //these two
        Date d = new Date();
        DateFormat date = new SimpleDateFormat("dd/MM/yyyy");
        DateFormat hour = new SimpleDateFormat("HH:mm:ss");
        if (date.equals(yourDate) && hour.equals(yourHour)){
            Intent it =  new Intent(context, MainActivity.class);
            createNotification(context, it, "Time to refresh", "Take a Deep Breath", "It's time for your daily meditation");
        }
    }catch (Exception e){
        Log.i("date","error == "+e.getMessage());
    }
}


public void createNotification(Context context, Intent intent, CharSequence ticker, CharSequence title, CharSequence descricao){
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    PendingIntent p = PendingIntent.getActivity(context, 0, intent, 0);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setTicker(ticker);
    builder.setContentTitle(title);
    builder.setContentText(descricao);
    builder.setSmallIcon(R.drawable.meditatebutton);
    builder.setContentIntent(p);
    Notification n = builder.build();
    //create the notification
    n.vibrate = new long[]{150, 300, 150, 400};
    n.flags = Notification.FLAG_AUTO_CANCEL;
    nm.notify(R.drawable.meditatebutton, n);
    //create a vibration
    try{

        Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone toque = RingtoneManager.getRingtone(context, som);
        toque.play();
    }
    catch(Exception e){}
}}


如您所见,我必须设置值在只能由主类访问的TextView中的your-date和your-hour变量,如何在各类之间共享这些值并解决此问题?

ps-我正在根据此Set notification for specific date and time实现这些类

最佳答案

试试这个

Intent intent = new Intent("com.example.Broadcast");
intent.putExtra("date", datetime);
sendBroadcast(intent);


在MyClass中

public void onReceive(Context context, Intent intent) {
 String action = intent.getAction();

 if(action.equals("com.example.Broadcast")){
  String dateTime = intent.getExtras().getString("date");
 }
}


在您的android清单文件中

<receiver android:name="MyReceiver" >
<intent-filter>
    <action android:name="com.example.Broadcast" >
    </action>
</intent-filter>




有关更多信息,请检查
this link

关于java - 如何将值从单个 View (布局)传递到多个Java类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57789756/

10-15 16:09