从广播接收器更新ui

时间:2015-10-28 11:27:57

标签: android broadcastreceiver

我有一个MainActivity,我想在每2分钟调用一次AlarmManager后更新UI ..请帮我怎么做

这是我的MainActivity

   public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
GPSTracker gps;
TextView lat1, long1;
Button exit, refresh;
private PendingIntent pendingIntent;
private static MainActivity mInst;
double newLat, newLong;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.app_bar);
    toolbar.setTitle("PWD_GPSFinder");
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    lat1 = (TextView) findViewById(R.id.latitude);
    long1 = (TextView) findViewById(R.id.longitude);
    exit = (Button) findViewById(R.id.button);
    exit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
    refresh = (Button) findViewById(R.id.buttonRefresh);

    Intent alarmIntent = new Intent(MainActivity.this, BroadcastReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
    startAlarm();


    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gps = new GPSTracker(MainActivity.this);

            // check if GPS enable
            if(gps.canGetLocation()){

                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
                lat1.setText(""+latitude);
                long1.setText(""+longitude);

            }else{
                gps.showSettingsAlert();
            }
        }
    });

    gps = new GPSTracker(MainActivity.this);

    // check if GPS enabled
    if(gps.canGetLocation()){

        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();
        lat1.setText(""+latitude);
        long1.setText(""+longitude);

    }else{

        gps.showSettingsAlert();
    }

}


public void startAlarm(){
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    /* Repeating on every 20 minutes interval */
    manager.setRepeating(AlarmManager.RTC_WAKEUP, 0,
            10 * 60 * 20, pendingIntent);
     Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}



@Override
protected void onResume() {

    super.onResume();
    // Other onResume() code here
    this.registerReceiver(mMessageReceiver, new IntentFilter("some_unique_name"));
}

@Override
protected void onPause() {
    super.onPause();
    this.unregisterReceiver(mMessageReceiver);
    // Other onPause() code here

}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        // Extract data included in the Intent
        String message = intent.getStringExtra("lat");
        String msg2 = intent.getStringExtra("long");
        updateYourActivity(context);
        lat1.setText(""+message);
        long1.setText(""+msg2);
        //update the TextView
        Toast.makeText(context, "Alarm Settttttttt", Toast.LENGTH_SHORT).show();
    }
};

private void updateYourActivity(Context context) {

    Intent intent = new Intent("some_unique_name");

    // put whatever data you want to send, if any
    // intent.putExtra("message", message);

    // send broadcast
    Toast.makeText(context, "Alarm Setdfdgdfgdfgtt", Toast.LENGTH_SHORT).show();
    newLat = gps.getLatitude();
    newLong = gps.getLongitude();
    intent.putExtra("lat", newLat);
    intent.putExtra("long", newLong);

    context.sendBroadcast(intent);


}

}

和AlarmReceiver类

 public class AlarmReceiver extends BroadcastReceiver {
GPSTracker gps;
String strDateTime;
String strDate;
FileWriter writer;
public static String username1;
File gpxfile;
File gpxfile1;
double latitude;
double longitude;

@Override
public void onReceive(Context context, Intent intent) {

    gps = new GPSTracker(context);

    // check if GPS enabled
    if(gps.canGetLocation()){

        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();
       // lat1.setText(""+latitude);
        //long1.setText(""+longitude);


    }else{
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        gps.showSettingsAlert();
    }
}

如何在这里设置TextView的值?请帮帮我。

1 个答案:

答案 0 :(得分:2)

从BroadcastReciever更新活动的一种方法是在MainActivity中创建一个BroadcastReciever:

  private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
     @Override
     public void onReceive(Context context, Intent intent) {

    // Extract data included in the Intent
    // String message = intent.getStringExtra("message");
    //update the TextView
  }
};

在onResume中重新启动此BroadcastReciever:

  this.registerReceiver(mMessageReceiver, new IntentFilter("some_unique_name"));

和unregiester onPause:

  this.unregisterReceiver(mMessageReceiver);

在AlarmReceiver中只需使用:

private void updateYourActivity(Context context) {

  Intent intent = new Intent("some_unique_name");

  // put whatever data you want to send, if any
  // intent.putExtra("message", message);

  // send broadcast
  context.sendBroadcast(intent);
}