如何自动触发警报管理器而不是onClick

时间:2013-05-20 07:45:55

标签: android triggers alarmmanager

下面是我的代码,它工作得非常好。我使用Alarm Manager点击按钮10秒后呼叫服务。我希望自动执行此过程,例如每10分钟它应自行触发并调用服务,而不管SCREEN_OFF或SCREEN_ON中的设备如何。目前我还怀疑来自“活动”的呼叫,因为如果我关闭应用程序它将不会触发。

/*MainActivity.java*/
package com.example.alarmservice;

public class MainActivity extends Activity implements OnClickListener{

final static private long ONE_SECOND = 1000;
final static private long TEN_SECONDS = ONE_SECOND * 10;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
@Override
protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       setup();
       findViewById(R.id.the_button).setOnClickListener(this);
}


private void setup() {
    br = new BroadcastReceiver() {
           @Override
           public void onReceive(Context c, Intent i) {
                  Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();
                  }
           };
    registerReceiver(br, new IntentFilter("com.example.alarmservice"));
    //pi = PendingIntent.getBroadcast( this, 0, new Intent("com.authorwjf.wakeywakey"),0);
    //am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));

    Intent intent = new Intent(MainActivity.this, ServiceClass.class);
    pi = PendingIntent.getService(MainActivity.this, 0, intent, 0);
    am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);



}


@Override
public void onClick(View v) {

    // TODO Auto-generated method stub
    am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + TEN_SECONDS, pi);

}

@Override
protected void onDestroy() {
       am.cancel(pi);
       unregisterReceiver(br);
       super.onDestroy();
}
}

服务类

/*ServiceClass.java*/   
package com.example.alarmservice;

public class ServiceClass extends Service {

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    Log.d("Testing", "Service got created");
    Toast.makeText(this, "ServiceClass.onCreate()", Toast.LENGTH_LONG).show();
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
}

@Override
public void onStart(Intent intent, int startId) {
    // TODO Auto-generated method stub
    super.onStart(intent, startId);
    Toast.makeText(this, "ServiceClass.onStart()", Toast.LENGTH_LONG).show();
    Log.d("Testing", "Service got started");
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

}

0 个答案:

没有答案