以下は、非常にうまく機能している私のコードです。アラーム マネージャーを使用して、ボタンをクリックして 10 秒後にサービスを呼び出しています。このプロセスを自動化して、SCREEN_OFFまたはSCREEN_ONのデバイスに関係なく、10分ごとにトリガーし、サービスを呼び出す必要があります。現在、「アクティビティ」からの呼び出しも疑われます。そのため、アプリケーションを閉じてもトリガーされません。
/*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;
}
}