在活动中访问BroadcastReceiver方法onReceive()

时间:2019-04-29 05:55:26

标签: android android-activity interface broadcastreceiver

我已经为AlarmManager应用编写了一些相关代码。

我想做一些类似在活动中做吐司按摩的事情,以确保我不能在onReceive()方法中做到这一点,问题是我如何在活动中做到这一点?

public class MainActivity extends AppCompatActivity implements View.OnClickListener,BroadConnect.IsConnect {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        vv();

        setRecurringAlarm(MainActivity.this);
    }

    private void setRecurringAlarm(Context context) {

        Calendar updateTime = Calendar.getInstance();
        //updateTime.setTimeZone(TimeZone.getTimeZone("GMT+5:00"));
        updateTime.setTimeZone(java.util.TimeZone.getTimeZone("GMT+5:00"));
        updateTime.set(Calendar.HOUR_OF_DAY,10);
        //updateTime.set(Calendar.MINUTE,31);
        updateTime.set(Calendar.MINUTE,1);
        updateTime.set(Calendar.SECOND,20);

        Intent intent = new Intent(context, BroadConnect.class);
        PendingIntent recurringDownload = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringDownload);
    }

    @Override
    public void onReceiveTimer() {
        Toast.makeText(MainActivity.this,"OK",Toast.LENGTH_LONG).show(); //This will not be displayed 
    }
}
public class BroadConnect extends BroadcastReceiver {

    private  IsConnect isConnect;

    public interface IsConnect{
        void onReceiveTimer();
    }

    public void setIsConnect(IsConnect isConnect) {
        this.isConnect = isConnect;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        isConnect.onReceiveTimer(); //It runs this and makes a ERRORE
    }
}

0 个答案:

没有答案