2012-04-19 10 views
17

私は携帯電話の現在位置を取得し、それにウェブサーバーを送るAndroidアプリを書いています。 私はスタートボタンを押して、アプリケーションが所定の間隔(例えば10分ごと)で場所を検索して送信し続け、別のボタンを押すとその場所を停止させたいと思っています。ここでボタンを押してから10分ごとにメソッドを繰り返し、別のボタンを押して終了するには

は私のボタンのコードです:

public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    startButton.setOnClickListener(new OnClickListener() { 
    @Override 
    //When the button is clicked 
    public void onClick(View v) { 
      finishButton.setEnabled(true); 
      startButton.setEnabled(false); 

      //Loops every 10mins 
      pingCurrentLocation(); 

     } 
    }); 

    finishButton.setOnClickListener(new OnClickListener() { 
    @Override 
    //When the button is clicked 
    public void onClick(View v) { 
      startButton.setEnabled(true); 
      finishButton.setEnabled(false); 

      pingCurrentLocation(); 

     } 
    }); 
} 

pingCurrentLocationは場所を取得し、それを送信する機能です。

私はAlarmManagerを使用するとおそらく私が望むことを達成できると知っていますが、私はそれを感知できませんでした。私の状況で動く明確なステップやテンプレートはありますか?

+1

私はそれを得ることはありません、アラームマネージャーはそれを行う理想的な方法です....私はアラームマネージャーを使用してまったく同じことをやっています。サービスはメモリを使い果たしてしまい、特にスレッドは好きではないので、私はAlarmManagerを選択しました。ここで私のコードを共有したいですか? – drulabs

+0

私は、それを実装する際に多くの問題を抱えていることが理想的であることを知っています。あなたのコードを共有しても大丈夫なら大丈夫です。 –

+0

@ X-Man - AlarmManager/BroadcastReceiverの組み合わせの使用に関する詳細を更新しました。 – coderplus

答えて

35

BroadcastReceiver

public class AlarmReceiver extends BroadcastReceiver 
{ 

@Override 
public void onReceive(Context context, Intent intent) 
    { 
    //get and send location information 
    } 
} 

を作成して、受信機は

<receiver 
    android:name="com.coderplus.AlarmReceiver" 
    android:exported="false"> 
</receiver> 

を登録されている今、あなたはすべての受信機を起動するあなたのActivityから繰り返しアラームを設定することができるように、あなたのAndroidManifestに同じを追加10分:

AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
Intent intent = new Intent(context, AlarmReceiver.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0); 
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),600000, 
                     pendingIntent); 

と、アラームを解除

PendingIntent同等
AlarmManager alarmManager=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
Intent intent = new Intent(context, AlarmReceiver.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0); 
alarmManager.cancel(pendingIntent); 

を使用してAlarmManagercancel()を呼び出すか、あなたはAlarmManager/BroadcastReceiverを使用したくない場合は、このようなものは、あなたを助けます。

Timer myTimer = new Timer(); 
MyTimerTask myTimerTask= new MyTimerTask(); 

Timer

//to Stop 
myTimer.cancel(); 
//to start 
myTimer.scheduleAtFixedRate(myTimerTask, 0, 600000); //(timertask,delay,period) 

http://developer.android.com/reference/java/util/TimerTask.html

を参照してくださいを停止または開始: - あなたはそれのために行く前に、チェック difference between timer and alarmmanager

private class MyTimerTask extends TimerTask { 
    @Override 
    public void run() {   
     //get and send location information 
    } 
} 

TimerTimerタスクを初期化します

http://developer.android.com/reference/java/util/Timer.html

+0

しかし、これは問題があります。 myTimer.scheduleAtFixedRate(myTimerTask、0、600000);を実行する開始ボタンを押して、停止/キャンセルボタンを押してから、もう一度startを押すと、アプリケーションがクラッシュします。 –

+0

@coderplus:メモリからアプリケーションを削除するとどうなりますか?それはまだ動作しますか? –

0

ユーザーの住所を確認するサービスを開始することができます&下記のように指定されたWebアドレスに送信します。

あなたはサービスhere

public class TaxiLocationUpdator extends Service{ 
    Location location; 
    Timer timer = new Timer(); 
    private final Handler handler = new Handler(); 
    Intent intent; 

    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    public void onCreate(){ 
     super.onCreate(); 
     updateNotification(); 
    } 

    //int onStartCommand(Intent intent, int flags, int startId) 
    public void onStart(Intent intent,int startId){ 
     super.onStart(intent, startId); 
     handler.removeCallbacks(sendUpdatesToUI); 
      handler.postDelayed(sendUpdatesToUI, 1000); // 1 second 
     Log.v("Location Servics", "Start Service"); 
    } 

    private Runnable sendUpdatesToUI = new Runnable() { 
      public void run() { 
       DisplayLoggingInfo();   
        handler.postDelayed(this, 15000); // 60 seconds here you can give your time 
      } 
     };  

    public void onDestroy(){ 
     super.onDestroy(); 
     Log.v("Location Servics", "Destroy Service"); 
    } 

    public boolean isOnline(){ 
      ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
      NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
      boolean isconnected; 
      if (netInfo==null || !netInfo.isConnected()) 
      isconnected=false; 
      else 
      isconnected=true; 
      Log.v("isOnliNe",isconnected+""); 
      return isconnected; 
     } 

    protected void updateNotification() { 
      LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
      LocationListener locationListener = new MyLocationlistener(); 

      lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, normallocationwait, 0.250f, locationListener); 
      location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     } 

     private class MyLocationlistener implements LocationListener { 

     public void onLocationChanged(Location location){ 
      if(location!=null){ 
       if(location.hasAccuracy()){ 
         dumpLocation(location); 
       }else{ 
         dumpLocation(location); 
       } 
      } 
     } 

     public void onProviderDisabled(String provider){ 
      Log.v("Loc Update","\nProvider disabled: " + provider); 
     } 

     public void onProviderEnabled(String provider){ 
      Log.v("Loc Update","\nProvider enabled: " + provider); 
     } 

     public void onStatusChanged(String provider, int status, Bundle extras){ 
      Log.v("Loc Update","\nProvider status changed: " + provider + ", status=" 
         + status + ", extras=" + extras); 
     } 

     private void dumpLocation(Location location) { 
       if (location == null) 
         Log.v("Loc Update","\nLocation[unknown]"); 
       else{ 
         Log.v("Loc Update","\n" + location.toString()); 
         Log.v("Demo", location.toString()); 
           String url = Your url; 
         Toast.makeText(getBaseContext(), "Location Update", Toast.LENGTH_SHORT).show(); 
         if(isOnline()){ 
          HttpClient httpclient = new DefaultHttpClient(); 
          HttpPost httppost = new HttpPost(url); 
          try { 
           HttpResponse response = httpclient.execute(httppost); 
           Log.v("Message", response.toString()); 
           } catch (ClientProtocolException e) { 
            Log.e("Sending Message",e.getMessage().toString()); 
           } catch (IOException e) { 
            Log.e("Sending Message",e.getMessage().toString()); 
          } 
        } 
       } 
      } 

     public boolean isOnline(){ 
      ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
      NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
      boolean isconnected; 
      if (netInfo==null || !netInfo.isConnected()) 
      isconnected=false; 
      else 
      isconnected=true; 
      Log.v("isOnliNe",isconnected+""); 
      return isconnected; 
     } 
    } 
} 
0

使用スレッドとストップコールの開始コール

alarmCheckThread.start(); 

のハンドラ

Handler alarmCheckHandler = new Handler() { 

     @Override 
     public void handleMessage(Message msg) { 
      super.handleMessage(msg); 

       System.out.println("getting message from alarm thread"); 
       //Call your function for ping 



    }; 
Thread alarmCheckThread = new Thread() { 
     public void run() { 
      int i = 0; 
      synchronized (this) { 
       while (checkflag) { 
        i++; 
        try { 
         sleep(1000); 
        } catch (InterruptedException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
        if (i == 600) { 
         alarmCheckHandler.sendMessage(alarmCheckHandler 
           .obtainMessage()); 
         i = 0; 
        } 

       } 
       System.out.println("End of unlimited while loop reched"); 
      } 
     } 
    }; 

に関する詳細な情報を得ることができます

alarmCheckThread.interrupt(); 
+1

'interrupt'は廃止予定です。どのように停止するのですか? – zionpi

3

ここに私がしたことがあります。

は、最初のアラームマネージャオブジェクトを作成し、繰り返しタイマー

意図をキャプチャし、それが指定した間隔でのコードだ実行されることを意図名前に基づいて活動を作成し
AlarmManager alarmMgr = alarmMgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
Intent alarmIntent = alarmIntent = new Intent("AlarmIntentReceiver"); 
PendingIntent pendingAlarmIntent = pendingAlarmIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, alarmIntent, 0); 
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 30*1000, 3*60*1000, pendingAlarmIntent); //start in 30 secs and rest in 3 mins interval 

を設定し、あなたも作成することができますあなたが好きなら放送受信機。

ボタンのクリックイベントでキャンセルします。これを書いてください

alarmMgr.cancel(pendingAlarmIntent); 
+0

'context'とは何ですか?その価値は何ですか?ごめんなさい。 –

+2

コンテキストは、アプリケーション環境に関するグローバル情報へのインタフェースです。これは、Androidシステムによって実装が提供される抽象クラスです。アプリケーション固有のリソースやクラスへのアクセス、起動アクティビティ、放送や受信インテントなどのアプリケーションレベルの操作のアップコールが可能です。詳細はこちら(http://developer.android.com/参照/アンドロイド/コンテンツ/ Context.html)...あなたがコンテキストを理解していない場合、おそらく最初にいくつかのアンドロイドの基礎を通過する必要があります... – drulabs

+0

コードで私は 'this'としてコンテキストを使用することができます右? –

関連する問題