よりもむしろあなたのService
を残しての書き込み権限がこの
startService(new Intent(this, MyService.class));
を書く私のコード活動の
public class MyService extends Service {
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
Random r;
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
r=new Random();
//
int o=r.nextInt(1000);
HttpPost postMethod = new HttpPost("http://androidsaveitem.appspot.com/save");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("description+", "description FOR id "+String.valueOf(o)));
formparams.add(new BasicNameValuePair("id+", String.valueOf(o)));
UrlEncodedFormEntity entity;
try {
entity = new UrlEncodedFormEntity(formparams);
postMethod.setEntity(entity);
DefaultHttpClient hc = new DefaultHttpClient();
try {
HttpResponse response = hc.execute(postMethod);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ですいつもバックグラウンドで走っている(常に仕事をしていない限り!)、 OSにアラームを登録して、指定された間隔でサービスを起動し、終了したらスリープ状態に戻すことを検討するべきでしょう。
これにより、Service
の実装が簡素化され、ほとんどのタイミング関連の問題が解決されます。 Service
が何らかの理由でクラッシュしたり死亡したりすると、アラームタイマーが次のサイクルに戻ってくるという利点もあります。
Android's AlarmManager
で登録したIntent
をリッスンしているBroadcastReceiver
を作成することです。
どのオプションを選択するかは、アラームのブロードキャストがタイマー待機よりもはるかに高額であるため、間隔の大きさに大きく左右されます。数秒ごとに作業をしたいなら、おそらくタイマーが良いでしょう。あなたの待ち時間が数分または数時間で測定されるならば、警報のことをしてください。
まず、アラームを作成する必要があります。
PendingIntent pi = PendingIntent.getService(context, 0, yourIntent, yourFlags);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setInexactRepeating(AlarmManger.ELAPSED_REALTIME, // Alarm type
5000, // Time before first alarm
AlarmManager.INTERVAL_HOUR, // Alarm interval
pi); // Sent when alarm happens
アラームを実際に使用するには、アラームが鳴るのを待たなければなりません。そのためには、BroadcastReceiver
を作成する必要があります。
public class SnoozeButton extends BroadcastReceiver {
public void onReceive (Context context, Intent intent) {
if (thisIntentIsTheOneIWant(intent){
context.startService(intent);
}
}
private boolean thisIntentIsTheOneIWant(Intent intent) {
// Test here to make sure this intent is for your app
// and service. You may get Intents other than what
// you are interested in.
}
}
あなたのAndroidManifest.xml
であなたのBroadcastReciever
を宣言する必要があります。
mmmここで私はこれを作ることができますか? – Hanaa
あなたはタイマーのコードを書くことができます – Hanaa
thanksss しかし、それは動作しませんでしたURLにデータがありません:( – Hanaa