0

私はすでにURLにデータを渡すためのコードを終了しました、そしてそれはうまくいきました。しかし今、私はこれをバックグラウンドで行う必要があるので、アプリケーションが終了してもこれを行うためのサービスを作成します。サービスを開始したときの私の問題は、データを1回渡すのですが、時間間隔ごとにデータを渡す必要があるので、どうすればよいですか?

これは私のコードです

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();
}

}
}

アクティビティで私はこれを書きます

     startService(new Intent(this, MyService.class));

マニフェストファイルにすでに権限を書き込んでいます

    <service android:enabled="true" android:name=".MyService" />
    <uses-permission android:name="android.permission.INTERNET" />
4

1 に答える 1

0

常にバックグラウンドで実行し続けるのではなくService(常に作業を行っている場合を除きます!)、OSにアラームを登録して、指定した間隔でサービスをウェイクアップし、終了時にスリープ状態に戻すことを検討する必要があります。 。

これにより、実装が簡素化Serviceされ、タイミングに関連する問題のほとんどから解放されます。Serviceまた、クラッシュしたり、何らかの理由で殺されたりした場合、アラームタイマーが次のサイクルでそれを元に戻すという利点もあります。

それが機能する方法は、 Androidに登録しBroadcastReceiverた特定のものをリッスンするを作成することです。 IntentAlarmManager

アラームのブロードキャストはタイマーを待機させるよりもはるかにコストがかかるため、どちらのオプションを選択するかは、間隔の大きさに大きく依存します。数秒ごとに作業を行いたい場合は、タイマーの方がおそらく優れています。待機時間が数分または数時間で測定される場合は、目覚まし時計を使用してください。

まず、アラームを作成する必要があります。

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.
    }
}

で宣言する必要があることに注意してBroadcastRecieverくださいAndroidManifest.xml

于 2012-03-24T16:42:38.057 に答える