1

下面是我的代码,它工作得很好。我在使用警报管理器单击按钮 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;
}

}
4

0 回答 0