无法从我的警报管理器的广播接收器修改活动

时间:2019-03-04 22:45:20

标签: java android android-broadcastreceiver

我想修改我的计划,该计划是每天午夜12点的应用数据库。我也想修改我的活动,该活动显示根据计划信息每天应更改的某些数字。我可以使用警报管理器来更新数据库,但无法更改活动的文本视图。它给了我这个错误: java.lang.ClassCastException: android.app.ReceiverRestrictedContext cannot be cast to com.example.bleh.myapplication.feature2

这是我的警报接收器类:

package com.example.bleh.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bleh.myapplication.DB.AppDatabase;
import com.example.bleh.myapplication.DB.Plan;
import com.example.bleh.myapplication.DB.User;
import com.example.bleh.myapplication.Utils1.FormulaUtils;
import com.github.lzyzsd.circleprogress.DonutProgress;

public class AlarmReceiver extends BroadcastReceiver {

    private static final String DEBUG_TAG = "AlarmReceiver";
    public AppDatabase mydb;
    Plan plan;

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
        mydb = AppDatabase.getInstance(context);
        final long planid = intent.getExtras().getLong("planid");
        final long userid = intent.getExtras().getLong("uid");
        final String requirements = intent.getExtras().getString("requirements");
        Log.wtf("PlanId: ",planid+"");
        Log.wtf("UserId: ",userid+"");
        Log.wtf("Requirements",requirements);
        plan = mydb.getPlanDao(context).getPlanById((int) planid);
        final User user = mydb.getUserDao(context).getUserById((int) userid);
        plan.setCurrentWeight(FormulaUtils.reCalculateWeight(plan.getCurrentWeight(), Double.parseDouble(requirements)));
        plan.setBmr(Double.parseDouble(FormulaUtils.calculateBmr(user.getSex(), plan.getCurrentWeight(), user.getHeight(), user.getBirthDay())));
        plan.setNbOfDays(plan.getNbOfDays() - 1);
        mydb.getPlanDao(context).update(plan);
        TextView requirement = ((feature2)context).findViewById(R.id.requirements);
        TextView Days = ((feature2)context).findViewById(R.id.days);
        DonutProgress DailyProgress = ((feature2)context).findViewById(R.id.donut_progress);
        requirement.setText(FormulaUtils.CalulcateDailyRequirements(plan.getWorkoutPerWeek(), plan.getBmr()));
        Days.setText(plan.getNbOfDays()+"");
        int progress = 0;
        DailyProgress.setProgress((float) progress);
//        Intent newIntent = new Intent(context, feature2.class);
//        newIntent.putExtra("uid", userid);
//        newIntent.putExtra("planid", planid);
//        context.startActivity(newIntent);
    }

}

这是我的专题活动(部分):

public class feature2 extends AppCompatActivity {

    public AppDatabase mydb;
    TextView BMR,requirements,days;
    Button addfood,addex,nextday;
    LinearLayout mainLayout;
    Button Meas,Bluetooth;
    DonutProgress donutProgress;
    Plan plan;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feature2);
        Intent intent = getIntent();
        requirements = findViewById(R.id.requirements);
        donutProgress = findViewById(R.id.donut_progress);
        days = findViewById(R.id.days);
        final long planid = intent.getExtras().getLong("planid");
        final long userid = intent.getExtras().getLong("uid");
        mydb = AppDatabase.getInstance(feature2.this);
        plan = mydb.getPlanDao(feature2.this).getPlanById((int) planid);
        requirements.setText(FormulaUtils.CalulcateDailyRequirements(plan.getWorkoutPerWeek(), plan.getBmr()));
        Intent intent1 = new Intent(this, AlarmReceiver.class);
        intent1.putExtra("uid", userid);
        intent1.putExtra("planid", planid);
        intent1.putExtra("requirements",requirements.getText().toString());
        Calendar updateTime = Calendar.getInstance();
        updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
        updateTime.set(Calendar.HOUR_OF_DAY, 20);
        updateTime.set(Calendar.MINUTE, 03);
        updateTime.set(Calendar.SECOND,0);
        Date milliseconds = updateTime.getTime();
        Log.wtf("millisec",milliseconds+"");
        long millis = milliseconds.getTime();
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
                intent1, PendingIntent.FLAG_ONE_SHOT);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, millis , pendingIntent);
        Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();
   }
}

1 个答案:

答案 0 :(得分:0)

此行使您的应用崩溃

TextView requirement = ((feature2)context).findViewById(R.id.requirements);

contextReceiverRestrictedContext的实例,feature2是其父是AppCompatActivity的{​​{1}}的实例。 ContextThemeWrapper不是feature2的实例,这就是您的应用抛出ReceiverRestrictedContext并使应用崩溃的原因。

解决方案:解决问题的方法有很多,这里有一个简单的方法。

步骤1:ClassCastException类中,以AlarmReceiver开始feature2活动。

FLAG_ACTIVITY_SINGLE_TOP | FLAG_ACTIVITY_CLEAR_TOP

第2步:如果public class AlarmReceiver extends BroadcastReceiver { private static final String DEBUG_TAG = "AlarmReceiver"; public AppDatabase mydb; Plan plan; @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show(); mydb = AppDatabase.getInstance(context); final long planid = intent.getExtras().getLong("planid"); final long userid = intent.getExtras().getLong("uid"); final String requirements = intent.getExtras().getString("requirements"); Log.wtf("PlanId: ",planid+""); Log.wtf("UserId: ",userid+""); Log.wtf("Requirements",requirements); plan = mydb.getPlanDao(context).getPlanById((int) planid); final User user = mydb.getUserDao(context).getUserById((int) userid); plan.setCurrentWeight(FormulaUtils.reCalculateWeight(plan.getCurrentWeight(), Double.parseDouble(requirements))); plan.setBmr(Double.parseDouble(FormulaUtils.calculateBmr(user.getSex(), plan.getCurrentWeight(), user.getHeight(), user.getBirthDay()))); plan.setNbOfDays(plan.getNbOfDays() - 1); mydb.getPlanDao(context).update(plan); // Calculate all data before sending to feature2 activity String requirement = FormulaUtils.CalulcateDailyRequirements(plan.getWorkoutPerWeek(), plan.getBmr()); String day = plan.getNbOfDays() + ""; float progress = 0F; // Start feature2 activity with updated data Intent updateFeature2Intent = new Intent(context, feature2.class); updateFeature2Intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); // Add this flag newIntent.putExtra("requirement", requirement); newIntent.putExtra("day", day); newIntent.putExtra("progress", progress); context.startActivity(newIntent); } } 活动在后台并且对用户可见,则将调用feature2,在这种情况下,获取数据并在那里更新UI。< / p>

onNewIntent