如我所见,没有任何方法可以将数据从“活动”传递到BroadCastReciever

时间:2018-09-26 23:30:09

标签: android android-intent broadcastreceiver alarmmanager

今天,我花了整整时间寻找一种方法,可以从MainActivity中将一些Integer数据传递给BroadCastReciever,但我没有找到任何方法来做,但我感到非常沮丧,我想做的是,我从用户那里获取一些小时,分钟和日期等整数数据并将其保存在SharedPreferences上,直到现在所有代码都能正常工作,然后我想为Broadcast实施电话重启时定义BroadCastreceiver并获取我保存在SharedPreferences上的数据 但我没有找到任何办法! 我一直尝试使用Intent或使构造器无效,因为BroadCast无法拥有构造器 请帮助我,如果您知道我该怎么做? 下面是我的代码

清单代码:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application
    android:name=".G"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Ring"></activity>

    <receiver android:name=".BroadCast">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>
</application>

MainActivity代码:

 //In this Activity i define 3 button , one for set TimePicker  and another one for 
 //set DatePicker and the last one for Save data and pass them To My instance BroadCast
 //so that when phone reboot, data save on SharedPreferences in My instance BroadCast
 //and after the phone turned on the data set and alarm work
 public class MainActivity extends AppCompatActivity {
 Button setBtn, dateBtn, saveBtn;
 public int sec = 0;
 public int min = 16;
 public int hour = 3;
 public int year = 2018;
 public int month = 8;
 public int day = 26;
 PendingIntent pendingIntent;
 Intent intent;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     intent = new Intent(this, Ring.class);
     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     pendingIntent = PendingIntent.getActivities(G.context, 0, new Intent[]  {intent}, PendingIntent.FLAG_UPDATE_CURRENT);
     setBtn = (Button) findViewById(R.id.setBtn);
     setBtn.setOnClickListener(new View.OnClickListener() {
         @Override
          public void onClick(View view) {
            TimePickerDialog dialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int Hour, int Min) {
                    hour = Hour;
                    min = Min;
                    Toast.makeText(MainActivity.this, Hour + " : " + Min + " : " + sec, Toast.LENGTH_SHORT).show();

                }
            }, 12, 0, true);
            dialog.show();


        }
    });
    dateBtn = (Button) findViewById(R.id.dateBtn);
    dateBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DatePickerDialog dialog1 = new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker datePicker, int Year, int Month, int Day) {
                    year = Year;
                    month = Month;
                    day = Day;
                    Toast.makeText(MainActivity.this, Year + " / " + Month + " / " + Day, Toast.LENGTH_SHORT).show();

                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.HOUR, hour);
                    calendar.set(Calendar.MINUTE, min);
                    calendar.set(Calendar.SECOND, sec);
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, month);
                    calendar.set(Calendar.DAY_OF_MONTH, day);
                    Log.i("LOG", hour + " : " + min + " : " + sec + "\n" + year + "//" + month + "//" + day);
                    G.alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                }
            }, 2018, 6, 12);
            dialog1.show();

        }
    });

    saveBtn = (Button) findViewById(R.id.saveBtn);
    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            passData();
        }
    });


}

public void passData() {
    Intent intent2 = new Intent(this, BroadCast.class);
    intent2.putExtra("HOUR", hour);
    intent2.putExtra("MIN", min);
    intent2.putExtra("YEAR", year);
    intent2.putExtra("MONTH", month);
    intent2.putExtra("DAY", day);
    sendBroadcast(intent2);
}

我的G应用程序类:

public class G extends Application {
public static Context context;
public static AlarmManager alarmManager;
@Override
public void onCreate() {
    super.onCreate();
    context = getApplicationContext();
    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}

}

我的实例BroadCast代码:

public class BroadCast extends BroadcastReceiver {
PendingIntent pendingIntent;
SharedPreferences sharedPreferences;

@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(G.context, "Reboot!", Toast.LENGTH_SHORT).show();
    Intent intent1 = new Intent(G.context, Ring.class);
    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    pendingIntent = PendingIntent.getActivities(G.context, 0, new Intent[]{intent1}, PendingIntent.FLAG_UPDATE_CURRENT);

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(G.context);

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt("HOUR", intent.getExtras().getInt("HOUR"));
    editor.putInt("MIN", intent.getExtras().getInt("MIN"));
    editor.putInt("YEAR", intent.getExtras().getInt("YEAR"));
    editor.putInt("MONTH", intent.getExtras().getInt("MONTH"));
    editor.putInt("DAY", intent.getExtras().getInt("DAY"));
    editor.commit();

//Here i log data and it works right and shows user's input data but after rebooring,
//Log shows 0 and alarm works a while after that
    Log.i("LOG1", sharedPreferences.getInt("HOUR", 0)
            + " : " + sharedPreferences.getInt("MIN", 0)
            + " : " + 0 + "\n" + sharedPreferences.getInt("YEAR", 0)
            + "." + sharedPreferences.getInt("MONTH", 0)
            + "." + sharedPreferences.getInt("DAY", 0));
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR, sharedPreferences.getInt("HOUR", 0));
    calendar.set(Calendar.MINUTE, sharedPreferences.getInt("MIN", 0));
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.YEAR, sharedPreferences.getInt("YEAR", 0));
    calendar.set(Calendar.MONTH, sharedPreferences.getInt("MONTH", 0));
    calendar.set(Calendar.DAY_OF_MONTH, sharedPreferences.getInt("DAY", 0));
    G.alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}

2 个答案:

答案 0 :(得分:0)

广播接收器的onReceive具有Context对象作为参数,您可以使用它来获取共享的首选项:

context.getSharedPreferences("MY_PREF",MODE_PRIVATE);

答案 1 :(得分:0)

发送广播时,您可以在Intent中添加其他内容:

Intent intent = new Intent(context,Receiver.class);
intent.putExtra("data",data);  //Here add your int as Extra
sendBroadcast(intent);

然后在您的接收器中:

void onReceive(Context context, Intent intent){
    int data = intent.getIntExtra("data");  //Get the data from extras
}