Search code examples
androidandroid-intentbroadcastreceiveralarmmanager

As I see There isn't Any way to pass data from Activity to a BroadCastReceiver


today I spent whole my time to find a way to pass some Integer data to my BroadCastReceiver from my MainActivity but I didn't find any way to do that and I'm totally depress, what I want to do is that I get some integer data like hour and minute and date from user and save them on SharedPreferences and til now all codes work right then I want to define a BroadCastreceiver for when the phone reboot this BroadCast implements and get my data that I save on SharedPreferences but I didn't find any way to do that! I try all the way like using Intent or making constructor that didn't work because the BroadCast can not have a constructor please help me if you know how can I do this? below is my codes

Manifest codes:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example9.kavoshrayan.org.alarm">

    <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>

</manifest>

MainActivity codes:

 //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);
}

My G Application Class:

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);
    }
}

My Instance BroadCast codes:

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);
}

Solution

  • You can add extras to the Intent when you send the broadcast like:

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

    And then in your Receiver:

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