0

나는 데이터를 url로 전달하는 코드를 이미 마쳤으며 성공적으로 수행했다. 하지만 이제는 백그라운드에서이 작업이 필요합니다. 따라서 응용 프로그램이 종료 된 경우에도이 작업을 수행하는 서비스를 만듭니다. 내 문제는 내가 한 번 데이터를 전달하는 서비스를 시작했지만 시간 간격마다 데이터를 전달해야합니다. 그렇게하는 방법 ?? URL에 데이터를 전달하는 안드로이드 서비스를 만드는 방법

내가이

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

이미 매니페스트 파일에 쓰기 권한을

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

mmm 어디에서 확인할 수 있습니까? – Hanaa

+0

제발 당신은 타이머 – Hanaa

+0

thanksss 에 대한 코드를 작성할 수 있습니까?하지만 그것은 거기에 아무런 데이터가 전달되지 않습니다 작동하지 않았다 : ( – Hanaa

답변

0

보다는 당신의 Service를 떠나 한 쓰기 활동에 내 코드

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을 만들어야합니다. 당신이 당신의 AndroidManifest.xmlBroadcastReciever를 선언해야

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

참고.

+0

그래, 내가 알람이 필요, 원인이 거의 간격이 필요합니다 하지만 당신이 할 수있는 예를 들어? – Hanaa

+0

@Hanaa 지금은 정교 할 시간이 없습니다. 나는 나중에 당신을 위해 모범을 보게 될 것입니다. – Argyle

+0

좋아, 오늘 시험해보십시오. – Hanaa

관련 문제