I am writing a kind of alarm clock for android, it will have to change the text in a TextView after a specified time, as I understand it is necessary to implement it in my class description BroadcastReceiver and get access to TextView in my activity, for this I do a static method in my activity and call it is from BroadcastReceiver, the alarm clock is working, but I think I am doing it all wrong and there is another way. Please tell me how else can you access TextView from BroadcastReceiver`a?
MainActivity code:
public class MainActivity extends AppCompatActivity{ static TextView showTime; EditText editTime; int str; final String LOG_TAG = "ml"; Intent intent; PendingIntent pi; AlarmManager am; static void setText(String text){ showTime.setText(text); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); showTime = (TextView)findViewById(R.id.textView); editTime = (EditText)findViewById(R.id.editText); am = (AlarmManager) getSystemService(ALARM_SERVICE); } Intent createIntent(String action, String extra) { Intent intent = new Intent(this, Receiver.class); intent.setAction(action); intent.putExtra(action,extra); return intent; } public void onClick(View view) { str = Integer.parseInt(editTime.getText().toString()); showTime.setText("your delay is " + str + " ms"); intent = createIntent("extra","qwerty"); pi = PendingIntent.getBroadcast(this,0,intent,0); am.set(AlarmManager.RTC,System.currentTimeMillis() + str,pi); } } code of my class Receiver:
public class Receiver extends BroadcastReceiver { final String LOG_TAG = "ml"; @Override public void onReceive(Context ctx, Intent intent){ Intent r = intent; String s = r.getStringExtra("extra"); MainActivity.setText(s); } }