Уведомление, созданное IntentService, всегда использует неправильное намерение - программирование
Подтвердить что ты не робот

Уведомление, созданное IntentService, всегда использует неправильное намерение

Проблема

Когда пользователь нажимает Send "Button 1" (прокрутите вниз, чтобы увидеть конструкцию приложения), новый Notification создается из RefreshService. Если пользователь нажимает это уведомление, экземпляр MainActivity запускается и получает String со значением Button 1 над Intent.

Это значение отображается.

При нажатии пользователем Send "Button 2" из RefreshService создается новый Notification. Если пользователь нажимает это уведомление, экземпляр MainActivity запускается и получает String ALSO со значением Button 1 над Intent.

Итак, как вы можете догадаться, обычно должно быть значение Button 2.

Когда первая кнопка, нажатая пользователем, была Send "Button 2", тогда всегда будет отправлено Button 2.

Единственное решение, чтобы получить значение второй кнопки, - это перезапустить телефон и сначала нажать вторую кнопку. Даже сила закрытия не работает.

Я знаю, что я также могу изменить интерфейс пользователя по-другому. Но мне нужен такой подход в приложении, где мне нужно перезапустить "MainActivity" с помощью другого Intent, чтобы подход был таким же.

Строительство

MainActivity

public class MainActivity extends Activity implements View.OnClickListener {
    public static final String RECEIVED = "received";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ((TextView)findViewById(R.id.textView_received)).setText(getIntent().getStringExtra(RECEIVED));

        findViewById(R.id.button_1).setOnClickListener(this);
        findViewById(R.id.button_2).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, RefreshService.class);

        if(v.getId() == R.id.button_1){
            intent.putExtra(RECEIVED, "Button 1");
            Toast.makeText(this,"Sent \"Button 1\"",Toast.LENGTH_LONG).show();
        }
        else if(v.getId() == R.id.button_2){
            intent.putExtra(RECEIVED, "Button 2");
            Toast.makeText(this,"Sent \"Button 2\"",Toast.LENGTH_LONG).show();
        }

        startService(intent);
    }
}

RefreshService

public class RefreshService extends IntentService {
    public RefreshService() {
        super("RefreshService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String received = intent.getStringExtra(MainActivity.RECEIVED);

        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.putExtra(MainActivity.RECEIVED, received);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentTitle("IntentServiceRefresh").setContentText(received).setSmallIcon(R.drawable.ic_notification_small).setContentIntent(pendingIntent);
        Notification notification = builder.build();

        // Hide the notification after it selected
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notification);
    }
}

Макет приложения
App Layout

4b9b3361

Ответ 1

Мое подозрение в том, что, поскольку единственное, что меняется в намерении, - это дополнительные функции, метод PendingIntent.getActivity(...) factory просто повторно использует старое намерение в качестве оптимизации.

В RefreshService попробуйте:

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

См:

http://developer.android.com/reference/android/app/PendingIntent.html#FLAG_CANCEL_CURRENT