2016-08-29 9 views
0

私の最初のアンドロイドアプリで作業しているので、私はおそらく愚かな間違いをしています。これは、トグルボタンを再クリックすると機能しますが、週番号が変更された場合に通知が自動的に更新され、通知が自動的に更新されます。私のコードのスニペットが含まれています。事前に助けてくれてありがとう。定期的にAndroidの通知が定期的に更新されない(ハンドラーの問題?)

import android.app.NotificationManager; 
import android.content.Context; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.support.v7.app.NotificationCompat; 
import android.util.Log; 
import android.os.Handler; 
import android.widget.CompoundButton; 
import android.widget.ToggleButton; 

import java.util.Calendar; 

public class MainActivity extends AppCompatActivity { 

    private static final String TAG = "MyActivity"; 


    public void createNotification() { 

     final Calendar now = Calendar.getInstance(); 
     now.get(Calendar.WEEK_OF_YEAR); 

     int weekId = 1; 
     final NotificationCompat.Builder nBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this) 
       .setContentTitle("Week") 
       .setContentText(""+now.get(Calendar.WEEK_OF_YEAR)) 
       .setSmallIcon(R.drawable.ic_stat_name); 
     final NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     NM.notify(weekId, nBuilder.build()); 

    } 

    // Init 
    private Handler handler = new Handler(); 
    private Runnable runnable = new Runnable() { 
     @Override 
     public void run() { 
      createNotification(); 
      Log.i(TAG, "updated"); 
      handler.postDelayed(runnable,1000); 
     } 
    }; 

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

     ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton); 
     toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       if (isChecked) { 
        // The toggle is enabled 
        createNotification(); 
       } else { 
        // The toggle is disabled 
        NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
        NM.cancelAll(); 
       } 
      } 
     }); 
    } 


} 

答えて

0

handler.postDelayed(runnable,1000)run()が呼び出されることはありませんされているので、呼び出されませんさん。ボールを転がすには、 'onCreate()'にhandler.postDelayed(runnable,1000)を追加してみてください。

+0

感謝を!今働いている。その興味深いのは、 "onCreate"のハンドラを一度実行すると、元のハンドラを参照しているように見え、 "onCreate"を "終了"している間もループし続けているように見えます。 – UberNoob

0

これが働いた:助けを

if (isChecked) { 
    // The toggle is enabled 
    handler.postDelayed(runnable,1000); 
} else { 
    // The toggle is disabled 
    NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    NM.cancel(1); 
} 
関連する問題