0

我如何运行一段代码让我们说每 1 秒?

这是我的代码
片段:MainActivity:

 private Context ctx;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button btn = (Button)findViewById(R.id.button1);
            ctx = this;
            btn.setOnClickListener(new OnClickListener(){

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                      AlarmManager am  = (AlarmManager)getSystemService(ALARM_SERVICE);
                      Calendar cal = Calendar.getInstance();
                      int inter =  1000;
                      Intent i = new Intent(ctx, Brodcast.class);
                      PendingIntent pi = PendingIntent.getBroadcast(ctx, 0, i, 0);
                      am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), inter, pi);
                }

            });
        }

广播类:

public class Brodcast extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub
        Toast.makeText(arg0, "This wil appear every one seconde", Toast.LENGTH_LONG).show();
        Log.e("this will apear every one seconde" , "this will apear every one seconde");
    }

}

但是日志和吐司都没有显示为什么???请帮忙。

4

1 回答 1

1

请确保您已在清单文件中定义了广播接收器,或者您使用评论中建议的代码注册它。

于 2013-10-17T14:37:51.327 回答