簡體   English   中英

無法從我的警報管理器的廣播接收器修改活動

[英]Not Able to modify an Activity from my Broadcast Receiver of Alarm Manager

我想修改我的計划,該計划是每天午夜的應用程序數據庫。 我也想修改我的活動,該活動顯示根據計划信息每天應更改的某些數字。 我可以使用警報管理器來更新數據庫,但無法更改活動的文本視圖。 它給了我這個錯誤: 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();
   }
}

這行使您的應用崩潰

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

contextReceiverRestrictedContext一個實例, feature2是其父為ContextThemeWrapperAppCompatActivity的一個實例。 feature2不是ReceiverRestrictedContext的實例,這就是您的應用程序引發ClassCastException並使應用程序崩潰的原因。

解決方案:解決問題的方法有很多,這里有一個簡單的方法。

步驟1:AlarmReceiver類中,使用feature2 FLAG_ACTIVITY_SINGLE_TOP | FLAG_ACTIVITY_CLEAR_TOP啟動feature2活動FLAG_ACTIVITY_SINGLE_TOP | FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_SINGLE_TOP | FLAG_ACTIVITY_CLEAR_TOP

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

第2步:如果feature2活動位於堆棧上並且對用戶可見,則將調用onNewIntent ,在這種情況下,獲取數據並在那里更新您的UI。

public class feature2 extends AppCompatActivity {

    ...

    // Add this method
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        // Get data from intent
        String requirement = intent.getStringExtra("requirement");
        String day = intent.getStringExtra("day");
        float progress = intent.getFloatExtra("progress", 0F);

        // Update UI
        TextView requirements = findViewById(R.id.requirements);
        TextView Days = findViewById(R.id.days);
        DonutProgress dailyProgress = findViewById(R.id.donut_progress);

        requirements.setText(requirement);
        Days.setText(day);
        dailyProgress.setProgress(progress);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM