0

При включении приложения каждую минуту должно выскакивать notification и оно выскакивает, но если повернуть экран, а потом вернуть в исходное положение, то оно начинает выскакивать не один раз, а три раза в подряд. Я так понимаю на каждое из активити MainActivity, ListActivity и CheckBoxActivity. Как можно этого избежать?

public class MainActivity extends TabActivity {

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

TabHost tabHost = getTabHost();

TabHost.TabSpec tabSpec;

tabSpec = tabHost.newTabSpec("tag1");
tabSpec.setIndicator(" List ");
tabSpec.setContent(new Intent(this, ListActivity.class));
tabHost.addTab(tabSpec);

tabSpec = tabHost.newTabSpec("tag2");
tabSpec.setIndicator(" CheckBox ");
tabSpec.setContent(new Intent(this, CheckBoxActivity.class));
tabHost.addTab(tabSpec);

NotificationService.start(this);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();

if (id == R.id.action_settings) {
    return true;
}

return super.onOptionsItemSelected(item);
}
}

NotificationService.java

public class NotificationService extends IntentService {

public NotificationService() {
    super("NotificationService");
}

private static final String START_SEND_NOTIFICATION = "start_send_notification";
private final Handler handler = new Handler();
private NotificationManager notificationManager;


// method for start service
public static void start(Context context) {
Intent intent = new Intent(context, NotificationService.class);
intent.setAction(START_SEND_NOTIFICATION);
context.startService(intent);
}

@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
    final String action = intent.getAction();
    switch (action) {
        case START_SEND_NOTIFICATION:
            showNotification();
                runnable.run();
            break;
    }
}
}


private  int counter = 0;

private Runnable runnable = new Runnable() {
public void run() {
    System.out.println("Conunt: " + counter);
    counter++;
    if (counter>60){
        showNotification();
        counter = 0;
    }

    handler.postDelayed(this, 710);

    //handler.removeCallbacks(this);

}
};

private void showNotification() {
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
System.out.println("<<Showing notification>>");

Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setTicker("New notification")
        .setWhen(System.currentTimeMillis())
//                    .setAutoCancel(true)
        .setContentText("Hello")
        .setProgress(100,20,true);

Notification notification = builder.build();

notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
notification.defaults |= Notification.DEFAULT_SOUND;


notificationManager.notify(1,notification);

} }

AndroidManifest.xml

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
    android:name=".activities.MainActivity"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<activity android:name=".activities.ListActivity"/>
<activity android:name=".activities.CheckBoxActivity"/>

<service android:name=".service.NotificationService"/>

</application>
1
  • для того, чтоб это избежать необходимо понять, что при повороте экрана Activity проживает такой цикл: onPause() onStop() onDestroy() onCreate() onStart() onResume() 9 янв 2016 в 12:54

1 ответ 1

2

Имеется код:

private Runnable runnable = new Runnable() {
    public void run() {
        System.out.println("Conunt: " + counter);
        counter++;
        if (counter>60){
            showNotification();
            counter = 0;
        }
        handler.postDelayed(this, 710);
    }
};

Который помещает неявную ссылку на MainActivity в NotificationService, которая, судя из кода, будет хранится 710 * 60 миллисекунд. Это значит, что сборщик мусора не сможет собрать твою активити при повороте экрана в течение этого времени. А собирать её надо, потому что когда ты переворачиваешь экран, создается новый инстанс активити, т.е. повернув 2 раза ты получаешь 3 экземпляра активити - отсюда и 3 нотификэйшена.

Можно решить проблему используя WeakHandler - это библиотека от Badoo. http://habrahabr.ru/company/badoo/blog/240479/ в этой статье все написано

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.