如何从AlarmManager BroadcastReceiver调用MainActivity方法



我有一个警报器,每天都会在特定的时间启动。我已经测试了发射,它有效。

现在,当警报响起时,我想从MainActivity调用updateTextView(),这将更改activity_main.xml中的TextView。我在这里尝试了很多解决方案:要么我不理解,要么它们不起作用。

主要活动:

public class MainActivity extends AppCompatActivity {
public TextView dailyTextView;
//TESTING
private static final String TAG = "MyActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dailyTextView = findViewById(R.id.main_text);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 13);
calendar.set(Calendar.MINUTE,25);
startAlarm(calendar);
}
public void updateTextView() {
...
}
private void startAlarm(Calendar calendar) {
Toast.makeText(this,"ALARM TEST",Toast.LENGTH_LONG).show();
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, DailyUpdateReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,1, intent,0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}

广播接收器:

public class DailyUpdateReceiver extends BroadcastReceiver {
private static final String TAG = "MyActivity";
//TODO: WORK ON THIS
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "ON RECEIVE STARTED!!!!!!!!!!!!!!!!!!!!!!");
}
}

在接收器中

@Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, MainActivity.class);
intent1.putExtra("type", 4);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
}

在您的主活动oncreate()

Intent intent = getIntent();
int TYPE = intent.getIntExtra("type",4);
if(TYPE == 4)
{
updateTextView();
}    

相关内容

  • 没有找到相关文章

最新更新