如何从alarmmanager broadcastreceiver调用mainactivity方法?

llycmphe  于 2021-07-04  发布在  Java
关注(0)|答案(1)|浏览(402)

我有一个闹钟,每天都会在特定的时间触发。我已经测试了射击效果。
现在,当警报响起时,我想打电话给你 updateTextView()MainActivity ,它改变了 TextViewactivity_main.xml . 我在这里尝试了许多解决方法:要么我不理解,要么它们不起作用。
主要活动:

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!!!!!!!!!!!!!!!!!!!!!!");

    }
}
brqmpdu1

brqmpdu11#

在你的听筒里

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

相关问题