生成具有图像视图的活动的新实例并将不同的图像分配给该图像视图

Generate new Instance of a actvity that has a imageview and assign a different image to that imageview

我可以从图库中挑选图像并将图像分配给 ImageView。偏好管理器在我离开时将图像保留在原位,return 到 activity。

我可以通过单击 ImageView 将那个图像更改为新图像。我需要的是一种创建相同 activity 的新实例的方法,其中只有 ImageView 中的图像被更改或更新。布局将保持不变,ImageView 中的图像将成为新实例中的新变量。感谢您的关注和帮助。迈克

  Thanks again : Here is Code  

AlarmDetailsActivity.Java:

public class AlarmDetailsActivity extends Activity {

private AlarmDBHelper dbHelper = new AlarmDBHelper(this);

private AlarmModel alarmDetails;

ImageView imageView ;

ImageView imageView2;

private static int RESULT_LOAD_IMAGE ;

private TimePicker timePicker;
private EditText edtName;
private CustomSwitch chkWeekly;
private CustomSwitch chkSunday;
private CustomSwitch chkMonday;
private CustomSwitch chkTuesday;
private CustomSwitch chkWednesday;
private CustomSwitch chkThursday;
private CustomSwitch chkFriday;
private CustomSwitch chkSaturday;
private TextView txtToneSelection;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_ACTION_BAR);

    setContentView(R.layout.activity_details);

    getActionBar().setTitle("Create New Alarm");
    getActionBar().setDisplayHomeAsUpEnabled(true);

    timePicker = (TimePicker)

    findViewById(R.id.alarm_details_time_picker);
    edtName = (EditText) findViewById(R.id.alarm_details_name);
    chkWeekly = (CustomSwitch) 
    findViewById(R.id.alarm_details_repeat_weekly);
    chkSunday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_sunday);
    chkMonday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_monday);
    chkTuesday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_tuesday);
    chkWednesday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_wednesday);
    chkThursday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_thursday);
    chkFriday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_friday);
    chkSaturday = (CustomSwitch)
    findViewById(R.id.alarm_details_repeat_saturday);
    txtToneSelection = (TextView) 
    findViewById(R.id.alarm_label_tone_selection);

    long id = getIntent().getExtras().getLong("id");

    if (id == -1) {
        alarmDetails = new AlarmModel();
    } else {
        alarmDetails = dbHelper.getAlarm(id);

        timePicker.setCurrentMinute(alarmDetails.timeMinute);
        timePicker.setCurrentHour(alarmDetails.timeHour);

        edtName.setText(alarmDetails.name);

        chkWeekly.setChecked(alarmDetails.repeatWeekly);

chkSunday.setChecked(alarmDetails.getRepeatingDay(AlarmModel.SUNDAY));
chkMonday.setChecked(alarmDetails.getRepeatingDay(AlarmModel.MONDAY));
chkTuesday.setChecked(alarmDetails.getRepeatingDay(AlarmModel.TUESDAY));

  ETC.



        txtToneSelection.setText(RingtoneManager.getRingtone(this,  
    alarmDetails.alarmTone).getTitle(this));
    }

    final LinearLayout ringToneContainer = (LinearLayout)
    findViewById(R.id.alarm_ringtone_container);
    ringToneContainer.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new 
    Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
            startActivityForResult(intent , 1);
        }
    });
    } 

   @Override
   protected void onActivityResult(int requestCode, int resultCode,  
   Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case 1: {
                alarmDetails.alarmTone =
    data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);

    txtToneSelection.setText(RingtoneManager.getRingtone(this,
    alarmDetails.alarmTone).getTitle(this));
                break;
            }
            default: {
                break;
            }
        }
    }





    Button button = (Button)findViewById(R.id.button1);

    button.setOnClickListener(new Button.OnClickListener(){



        @Override
        public void onClick(View v) {
             Intent i = new Intent(
                        Intent.ACTION_PICK,

      android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);

             Toast.makeText(getBaseContext(), "Set Image ",   
      Toast.LENGTH_LONG).show();
        }
      });
      } 


      public void onActivityResult (int requestCode, int resultCode,  
      Intent data, int SELECT_PICTURE, Intent intent, Uri selectedImage,
      Intent intent1 ) {


            if (requestCode == RESULT_LOAD_IMAGE && resultCode == 
           RESULT_OK && null != data) {



                String[] filePathColumn = { MediaStore.Images.Media.DATA
      };

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex =
      cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();



                ImageView imageView  = (ImageView)
      findViewById(R.id.imageView2);


      imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));


                BitmapFactory.Options options = new
      BitmapFactory.Options();
                options.inSampleSize = 6;
                options.inScaled = false;
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;

      imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath,  
      options));



            AlarmManager alarmManager = (AlarmManager)
      getSystemService(ALARM_SERVICE);
            // initializing our pending intent, this is where the magic
      happens :)
            // notice that we're using the intent from above, read more  
      about the method down below
            // notice the FLAG_UPDATE_CURRENT flag here, this will
      update our instance of previous
            // pending intents to the pending intent we have now
            PendingIntent pendingIntent =
      PendingIntent.getBroadcast(getApplicationContext(), 100,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

            // finally set the alarm manager, I'm using set here, but be
      sure to go through the 
            // documentation as there are other methods like 
      setRepeating(), etc
            // which may satisfy your need
            alarmManager.set(AlarmManager.RTC_WAKEUP,
      System.currentTimeMillis(), pendingIntent);
        }}


     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
     getMenuInflater().inflate(R.menu.alarm_details, menu);
     return true;
     }

     @Override
     public boolean onOptionsItemSelected(MenuItem item) {

     switch (item.getItemId()) {
        case android.R.id.home: {
            finish();
            break;
        }
        case R.id.action_save_alarm_details: {
            updateModelFromLayout();

            AlarmManagerHelper.cancelAlarms(this);

            if (alarmDetails.id < 0) {
                dbHelper.createAlarm(alarmDetails);
            } else {
                dbHelper.updateAlarm(alarmDetails);
            }

            AlarmManagerHelper.setAlarms(this);

            setResult(RESULT_OK);
            finish();
           }
           }

           return super.onOptionsItemSelected(item);
           }

           private void updateModelFromLayout() {       
           alarmDetails.timeMinute =    
           timePicker.getCurrentMinute().intValue();
           alarmDetails.timeHour =   
           timePicker.getCurrentHour().intValue();
           alarmDetails.name = edtName.getText().toString();
           alarmDetails.repeatWeekly = chkWeekly.isChecked();   
           alarmDetails.setRepeatingDay(AlarmModel.SUNDAY,   
           chkSunday.isChecked());  
           alarmDetails.setRepeatingDay(AlarmModel.MONDAY,   
           chkMonday.isChecked());  
    alarmDetails.setRepeatingDay(AlarmModel.TUESDAY,  
    chkTuesday.isChecked());
    alarmDetails.setRepeatingDay(AlarmModel.WEDNESDAY,  
    chkWednesday.isChecked());  
    alarmDetails.setRepeatingDay(AlarmModel.THURSDAY,
    chkThursday.isChecked());
    alarmDetails.setRepeatingDay(AlarmModel.FRDIAY,
    chkFriday.isChecked());
    alarmDetails.setRepeatingDay(AlarmModel.SATURDAY,
    chkSaturday.isChecked());
    alarmDetails.isEnabled = true;
    }

    public static int getRESULT_LOAD_IMAGE() {
    return RESULT_LOAD_IMAGE;
    }

    public static void setRESULT_LOAD_IMAGE(int rESULT_LOAD_IMAGE) {
    RESULT_LOAD_IMAGE = rESULT_LOAD_IMAGE;
    }

   ;}


   activity_details.xml:


  <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:isScrollContainer="true" >

  <!--
        <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".AlarmDetailsActivity" >
    -->

   <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context=".AlarmDetailsActivity" >

    <TimePicker
        android:id="@+id/alarm_details_time_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:id="@+id/alarm_details_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/alarm_details_time_picker"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:ems="10"
        android:hint="@string/details_alarm_name" />

      <View
        android:id="@+id/divider2"
        style="@style/Divider"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/alarm_details_name" />

      <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_weekly"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/divider2"
        android:checked="true"
        android:text="@string/details_repeat_weekly" />

        <View
        android:id="@+id/divider1"
        style="@style/Divider"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/alarm_details_repeat_weekly" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_sunday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/divider1"
        android:checked="true"
        android:text="@string/details_sunday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_monday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_sunday"
        android:layout_below="@+id/alarm_details_repeat_sunday"
        android:checked="true"
        android:text="@string/details_monday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_tuesday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_monday"
        android:layout_below="@+id/alarm_details_repeat_monday"
        android:checked="true"
        android:text="@string/details_tuesday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_wednesday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_tuesday"
        android:layout_below="@+id/alarm_details_repeat_tuesday"
        android:checked="true"
        android:text="@string/details_wednesday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_thursday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_wednesday"
        android:layout_below="@+id/alarm_details_repeat_wednesday"
        android:checked="true"
        android:text="@string/details_thursday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_friday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_thursday"
        android:layout_below="@+id/alarm_details_repeat_thursday"
        android:checked="true"
        android:text="@string/details_friday" />

        <com.Chloie.CustomSwitch
        android:id="@+id/alarm_details_repeat_saturday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/alarm_details_repeat_friday"
        android:layout_below="@+id/alarm_details_repeat_friday"
        android:checked="true"
        android:text="@string/details_saturday" />

        <View
        android:id="@+id/divider4"
        style="@style/Divider"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/alarm_details_repeat_saturday" />

        <LinearLayout
        android:id="@+id/alarm_ringtone_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/divider4"
        android:background="@drawable/view_touch_selector"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/alarm_label_tone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:text="@string/details_alarm_tone"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/alarm_label_tone_selection"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/activity_vertical_margin"
            android:text="@string/details_alarm_tone_default"
            android:textSize="14sp" />
         <View
              android:id="@+id/divider5"
              style="@style/Divider"
              android:layout_alignParentLeft="true"
              android:layout_below="@+id/alarm_ringtone_container" />

         <Button
             android:id="@+id/button1"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentBottom="true"
             android:layout_centerHorizontal="true"
             android:layout_gravity="center"
             android:text="Picture" />

           </LinearLayout>

           <View
           android:id="@+id/divider3"
           style="@style/Divider"
           android:layout_alignParentLeft="true"
           android:layout_below="@+id/alarm_ringtone_container" />
           </RelativeLayout>

           </ScrollView>



           AlarmScreen.java


           public class AlarmScreen extends Activity {

           public final String TAG = this.getClass().getSimpleName();

           private WakeLock mWakeLock;
           private MediaPlayer mPlayer;

           private static final int WAKELOCK_TIMEOUT = 60 * 1000;

           ImageView imageView2;


           @Override
           protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);

           //Setup layout
           this.setContentView(R.layout.activity_alarm_screen);

           String name =     
           getIntent().getStringExtra(AlarmManagerHelper.NAME);
           int timeHour =    
           getIntent().getIntExtra(AlarmManagerHelper.TIME_HOUR, 0);
           int timeMinute =   
           getIntent().getIntExtra(AlarmManagerHelper.TIME_MINUTE, 0);
           String tone = getIntent().get
           StringExtra(AlarmManagerHelper.TONE);

           TextView tvName = (TextView)  
           findViewById(R.id.alarm_screen_name);
           tvName.setText(name);

           TextView tvTime = (TextView)   
           findViewById(R.id.alarm_screen_time);
           tvTime.setText(String.format("%02d : %02d", timeHour,    
           timeMinute));

           Button dismissButton = (Button)   
           findViewById(R.id.alarm_screen_button);
           dismissButton.setOnClickListener(new OnClickListener() {

           @Override
           public void onClick(View view) {
            mPlayer.stop();
            mPlayer.release();
            finish();

            mPlayer = new MediaPlayer();

             mPlayer = MediaPlayer.create(AlarmScreen.this, R.raw.lunch);
                mPlayer.start();
            Intent alarmIntent = new Intent(getBaseContext(),  
            TimerActivity.class);
            alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            getApplication().startActivity(alarmIntent);




            //Play alarm tone
           mPlayer = new MediaPlayer();
           try {
           if (tone != null && !tone.equals("")) {
            Uri toneUri = Uri.parse(tone);
            if (toneUri != null) {
                mPlayer.setDataSource(this, toneUri);
                mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mPlayer.setLooping(true);
                mPlayer.prepare();
                mPlayer.start();
            }
            }
            } catch (Exception e) {
            e.printStackTrace();
             }

            //Ensure wakelock release
            Runnable releaseWakelock = new Runnable() {

           @Override
           public void run() {

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

            if (mWakeLock != null && mWakeLock.isHeld()) {
                mWakeLock.release();
            }
        }
    };

    new Handler().postDelayed(releaseWakelock, WAKELOCK_TIMEOUT);
    }

  protected android.content.Intent AlarmIntent(
        OnClickListener onClickListener, Class<Task> class1) {
    // TODO Auto-generated method stub
    return null;
   }

  protected <MainActivity> Intent Intent(OnClickListener onClickListener,
        Class<MainActivity> class1) {
    // TODO Auto-generated method stub
    return null;
   }

  @SuppressWarnings("deprecation")
    @Override
   protected void onResume() {
    super.onResume();

    // Set the window to keep screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

  getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

 getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

    // Acquire wakelock
    PowerManager pm = (PowerManager)  
 getApplicationContext().getSystemService(Context.POWER_SERVICE);
    if (mWakeLock == null) {
        mWakeLock = pm.newWakeLock((PowerManager.FULL_WAKE_LOCK |  
  PowerManager.SCREEN_BRIGHT_WAKE_LOCK |
  PowerManager.ACQUIRE_CAUSES_WAKEUP), TAG);
    }

    if (!mWakeLock.isHeld()) {
        mWakeLock.acquire();
        Log.i(TAG, "Wakelock aquired!!");
    }

     }

   @Override
   protected void onPause() {
    super.onPause();

    if (mWakeLock != null && mWakeLock.isHeld()) {
        mWakeLock.release();
    }
    }}

    activity_alarm_screen.xml:


    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res   
    /android"
    android:layout_width="match_parent"
     android:layout_height="match_parent" >

    <TextView
    android:id="@+id/alarm_screen_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="28dp"
    android:text="Alarm!"
    android:textSize="38dp" />

     <TextView
    android:id="@+id/alarm_screen_time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/alarm_screen_button"
    android:layout_below="@+id/alarm_screen_title"
    android:layout_marginTop="28dp"
    android:text="00 : 00"
    android:textSize="52dp" />

     <TextView
    android:id="@+id/alarm_screen_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/alarm_screen_time"
    android:layout_centerHorizontal="true"
    android:text="Alarm name" />

    <Button
    android:id="@+id/alarm_screen_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="16dp"
    android:text="Dismiss"
    android:textSize="38dp" />

    <ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/alarm_screen_button"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/alarm_screen_name" />

    </RelativeLayout>


    AlarmManagerHelper/BroadcastReceiver.Java:



    public class AlarmManagerHelper extends BroadcastReceiver {

    public static final String ID = "id";
    public static final String NAME = "name";
    public static final String TIME_HOUR = "timeHour";
    public static final String TIME_MINUTE = "timeMinute";
    public static final String TONE = "alarmTone";

    @Override
    public void onReceive(Context context, Intent intent) {
    setAlarms(context);
      intent.getParcelableExtra("my-uri");
     }   


     public static void setAlarms(Context context) {
     cancelAlarms(context);

      AlarmDBHelper dbHelper = new AlarmDBHelper(context);

      List<AlarmModel> alarms =  dbHelper.getAlarms();

      for (AlarmModel alarm : alarms) {
        if (alarm.isEnabled) {

            PendingIntent pIntent = createPendingIntent(context, alarm);

            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, alarm.timeHour);
            calendar.set(Calendar.MINUTE, alarm.timeMinute);
            calendar.set(Calendar.SECOND, 00);

            //Find next time to set
            final int nowDay =  
            Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
            final int nowHour =   
            Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
            final int nowMinute = 
            Calendar.getInstance().get(Calendar.MINUTE);
            boolean alarmSet = false;

            //First check if it's later in the week
            for (int dayOfWeek = Calendar.SUNDAY; dayOfWeek <= 
            Calendar.SATURDAY; ++dayOfWeek) {
                if (alarm.getRepeatingDay(dayOfWeek - 1) && dayOfWeek   
             >= nowDay &&
            !(dayOfWeek == nowDay && alarm.timeHour < nowHour) &&
            !(dayOfWeek == nowDay && alarm.timeHour == nowHour &&  
           alarm.timeMinute <= nowMinute)) {
                    calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);

                    setAlarm(context, calendar, pIntent);
                    alarmSet = true;
                    break;
                }
            }

            //Else check if it's earlier in the week
            if (!alarmSet) {
                for (int dayOfWeek = Calendar.SUNDAY; dayOfWeek <= 
           Calendar.SATURDAY; ++dayOfWeek) {
                    if (alarm.getRepeatingDay(dayOfWeek - 1) &&
           dayOfWeek <= nowDay && alarm.repeatWeekly) {
                        calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
                        calendar.add(Calendar.WEEK_OF_YEAR, 1);

                        setAlarm(context, calendar, pIntent);
                        alarmSet = true;
                        break;
                    }
                }
            }
         }
        }
       }

        @SuppressLint("NewApi")
        private static void setAlarm(Context context, Calendar calendar,
        PendingIntent pIntent) {
        AlarmManager alarmManager = (AlarmManager)
        context.getSystemService(Context.ALARM_SERVICE);
         if (android.os.Build.VERSION.SDK_INT >=  
         android.os.Build.VERSION_CODES.KITKAT) {
         alarmManager.setExact(AlarmManager.RTC_WAKEUP,
         calendar.getTimeInMillis(), pIntent);
          } else {
          alarmManager.set(AlarmManager.RTC_WAKEUP,
         calendar.getTimeInMillis(), pIntent);
         }
         }

         public static void cancelAlarms(Context context) {
        AlarmDBHelper dbHelper = new AlarmDBHelper(context);

         List<AlarmModel> alarms =  dbHelper.getAlarms();

         if (alarms != null) {
        for (AlarmModel alarm : alarms) {
            if (alarm.isEnabled) {
                PendingIntent pIntent = createPendingIntent(context,     
         alarm);

                AlarmManager alarmManager = (AlarmManager)
          context.getSystemService(Context.ALARM_SERVICE);
                 alarmManager.cancel(pIntent);
            }
          }
          }
         }

        private static PendingIntent createPendingIntent(Context   
        context, AlarmModel model) {
        Intent intent = new Intent(context, AlarmService.class);
         intent.putExtra(ID, model.id);
        intent.putExtra(NAME, model.name);
         intent.putExtra(TIME_HOUR, model.timeHour);
         intent.putExtra(TIME_MINUTE, model.timeMinute);
         intent.putExtra(TONE, model.alarmTone.toString());

          return PendingIntent.getService(context, (int) model.id,  
         intent, PendingIntent.FLAG_UPDATE_CURRENT);
         }
          }

如果您想将 ImageView 替换为用户从图库中选择的内容,则无需重新创建 Activity 的新实例。你可以得到一个 Intent 来为你做这件事。您必须执行 startActivityForResult() and your activity will have to override the onActivityResult() 回调。

基本上您的代码将类似于:

view.onClick() {
   Intent intent = new Intent();
   intent.setType("image/*");
   intent.setAction(Intent.ACTION_GET_CONTENT);
   startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}

在您的 onActivityResult() 上,务必获取图像的 Uri

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
        }
    }
}

有关详细信息,请参阅 this

编辑: 要为每个其他图像创建一个新的警报,您不必创建 Activity 的新实例,而是通过AlarmManager

manager.setExact(...)

并根据需要使用 PendingIntent's flag to update/创建警报。

在您的 onActivityResult() 回调中调用此方法。

编辑: 要使用警报,您需要做两件事(我假设您将使用 BroadcastReceiver):

1) 创建一个 BroadcastReceiver 来拦截警报调用。

我真的很喜欢广播接收器让处理这些类型的事件变得如此简单。

例如

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // do things you want here, with the current implementation
        // the alarm manager will invoke the receiver
        // use the intent param to fetch relevant information 
        Uri selectedImageUri = (Uri) intent.getParcelableExtra("my-uri");
    }   
}

不要忘记将接收器注册到您的 AndroidManifest.xml

2) 在你的 onActivityResult() 中初始化 AlarmManager

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            Intent intent = new Intent(this, MyReceiver.class);
            // i'm assuming that you'll need to pass to the image Uri to the receiver
            // you can include needed information into the intent as long as they are
            // primitive types, String, Serializable, arrays or Parcelable objects
            // since Uri's are Parcelable you send them through intents
            intent.putExtra("my-uri", selectedImageUri);
            ...

            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            // initializing our pending intent, this is where the magic happens :)
            // notice that we're using the intent from above, read more about the method down below
            // notice the FLAG_UPDATE_CURRENT flag here, this will update our instance of previous
            // pending intents to the pending intent we have now
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);

            // finally set the alarm manager, I'm using set here, but be sure to go through the 
            // documentation as there are other methods like setRepeating(), etc
            // which may satisfy your need
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);
        }
    }

getBroadcast(...)

处理所有这些 类 和文档现在可能看起来令人生畏,但给它一些时间并尝试理解代码。

有关不同 Apis 的更多示例,请查看 ApiDemo I'd also like to recommend this 应用程序。该应用程序包含大部分 ApiDemos,为您提供急需的视觉帮助 :)

事实证明答案和我想的一样,通过偏好选择和 selection.Lastly ImageView 目标的持久化解决了接收 activity 中没有明确设置的问题。

@ Rakeeb Rajbhandari 的回答被证明对如何前进非常有帮助。感谢 Rakeeb Rajbhandari 和其他可能对此问题感兴趣的人。