2013-03-19 46 views
0

MainAcivity.java背景傳感

package com.example.background_shake; 

import java.util.List; 
import java.util.Locale; 
import android.app.Activity; 
import android.content.Intent; 
import android.hardware.SensorManager; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.Window; 
import android.view.WindowManager; 
import android.widget.Button; 


public class MainActivity extends Activity implements OnClickListener { 
    Button ON,OFF; 
private SensorManager sensorManager; 
private long lastUpdate; 

Intent i1; 
public static final String TAG = "ServicesDemo"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 

    //reseting the window propertys 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
      WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    //super method 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    ON=(Button)findViewById(R.id.ON); 
    OFF=(Button)findViewById(R.id.OFF); 
    ON.setOnClickListener(this); 
    OFF.setOnClickListener(this); 
} 
public void onClick(View src) { 
    switch (src.getId()) { 
    case R.id.ON: 
     Log.d(TAG, "onClick: starting srvice"); 
     startService(new Intent(this, Background_service.class)); 
     break; 
    case R.id.OFF: 
     Log.d(TAG, "onClick: stopping srvice"); 
     stopService(new Intent(this, Background_service.class)); 
     break; 
    } 
} 
@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 
    } 

Background_service.java

package com.example.background_shake; 

import java.util.List; 
import java.util.Locale; 
import android.app.Service; 
import android.content.Intent; 
import android.hardware.Sensor; 
import android.hardware.SensorEvent; 
import android.hardware.SensorEventListener; 
import android.hardware.SensorManager; 
import android.location.Address; 
import android.location.Geocoder; 
import android.os.IBinder; 
import android.util.Log; 
import android.widget.Toast; 

public class Background_service extends Service implements SensorEventListener{ 
    boolean flag=false; 
    private long lastUpdate; 
    SensorManager sensorManager; 
      int count=0; 
@Override 
public IBinder onBind(Intent intent) { 

    return null; 
} 
public void onCreate() 
{ 
    flag=true; 
    Log.d(MainActivity.TAG, "onCreate"); 
    super.onCreate(); 

} 
public void onDestroy() { 

    flag=false; 
    Log.d(MainActivity.TAG, "onDestroy"); 
    super.onDestroy(); 

} 
public void onStart(Intent intent, int startId) 
{ 
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 
    sensorManager.registerListener(this, 
      sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
      SensorManager.SENSOR_DELAY_NORMAL); 
    lastUpdate = System.currentTimeMillis(); 
} 
@Override 
public void onAccuracyChanged(Sensor sensor, int accuracy) { 


} 
private void getAccelerometer(SensorEvent event) { 
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { 
    float[] values = event.values; 
    // Movement 
    float x = values[0]; 
    float y = values[1]; 
    float z = values[2]; 
    double latitude=0; 
    double longitude=0; 
    String location_message; 
    GPSTracker gps; 

    float accelationSquareRoot = (x * x + y * y + z * z) 
     /(SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH); 
    long actualTime = System.currentTimeMillis(); 
    if (accelationSquareRoot >= 2) // 
    { 
     if (actualTime - lastUpdate < 2000) { 
      count++; 
     return; 
     } 

     lastUpdate = actualTime; 

     { 
      gps=new GPSTracker(Background_service.this); 
      if((gps.canGetLocation())&&(count==3)){ 
         count=0;  
       latitude = gps.getLatitude(); 
       longitude = gps.getLongitude(); 
     // \n is for new line 
     // Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();  
       Geocoder gcd = new Geocoder(Background_service.this, Locale.getDefault()); 
       try{ 
        List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1); 
        location_message= addresses.get(0).getLocality(); 
        if ((addresses.size() > 0)&&(flag)) 
        { 
         Toast.makeText(getApplicationContext(), "Your Location is " +addresses.get(0).getLocality() 
           , Toast.LENGTH_LONG).show(); 
             count=0; 
        } 

       }catch(Exception e) 
       { 
        System.out.print(e); 
       } 
      }else{ 
     // can't get location 
     // GPS or Network is not enabled 
     // Ask user to enable GPS/network in settings 
     Toast.makeText(getApplicationContext(), "Switch on gps" 
       , Toast.LENGTH_LONG).show(); 
     gps.showSettingsAlert(); 
    }} 


     /*Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT) 
      .show(); 
     if (color) { 
     view.setBackgroundColor(Color.GREEN); 

     } else { 
     view.setBackgroundColor(Color.RED); 
     }*/ 

    }} 
    } 
public void onSensorChanged(SensorEvent event) { 

    getAccelerometer(event); 


} 
protected void onResume() { 
    //super.onResume(); 
    // register this class as a listener for the orientation and 
    // accelerometer sensors 
      sensorManager.registerListener(this, 
      sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
      SensorManager.SENSOR_DELAY_NORMAL); 
} 

protected void onPause() 
{ 
    // unregister listener 
    sensorManager.unregisterListener(this); 

} 

}

上面的代碼是用於感測抖動參數並給你的應用程序當前位置。 但問題是,即使我的GPS關閉,我正在獲取我的當前位置。

另外我想知道兩件事情 1.即使鎖定手機,服務是否也能正常工作?如果不是,必須對我的代碼進行哪些修改才能使用? 2.我的應用程序給出的輸出,如果我搖我的手機一次,但我希望我的應用程序給予所需的結果,只有當我連續搖動3-4次。是否有可能這樣做?

回答

0

Q1已經在這裏由akajaymo回答。

對於第二季度,而不是讓應用程序在每次手機抖動時產生所需的輸出,請創建兩個靜態變量int countlong last

每次電話被震動時,您都會檢查是否(System.currentTimeMillis() - last) < 1000/* considering the shakes are not more than 1 second apart */,如果是,則增加計數。

如果count達到3或4,則表示完成:只產生所需的輸出。如果不是,則什麼都不會產

如果奶昔比1000ms的更開,剛剛成立count爲1

而且,每次檢測出抖動時,請last = System.currentTimeMillis()。此更新至最後必須完成我提到的第一個檢查。

+0

我已在我的代碼中進行了必要的修改。但該應用程序不工作(強制關閉)。你能否請檢查我發佈的代碼並幫助我找到錯誤。 – 2013-03-19 10:37:58

+0

你可以請發佈錯誤(logcat所示的異常)?一旦你知道問題實際是什麼,找出問題更容易。 – 2013-03-19 13:06:07

+0

我試圖打印在我的程序數量的值,但它從來沒有得到增加 – 2013-03-20 10:20:12

3

要回答您的問題: 1.即使您鎖定手機,服務是否也能正常工作?如果否,必須對我的代碼進行哪些修改才能運行?

是的,一旦服務已經啓動,它將繼續無限地運行,但是如果電話切換並且希望服務在電話啓動後馬上啓動,您可以嘗試創建啓動時觸發的廣播接收器

public class Broadcastreceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Intent startSMSServiceIntent = new Intent(context, SOMEservice.class); 
     context.startService(startSMSServiceIntent); 
    } 
} 

在清單

<receiver android:name=".Broadcastreceiver">    
    <intent-filter> 
     <action android:name="android.intent.action.BOOT_COMPLETED" /> 
    </intent-filter>   
</receiver> 

不要忘記權限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
+0

這意味着如果我鎖定我的手機,並嘗試發送消息給另一個人搖晃它會工作正確嗎? – 2013-03-19 06:21:20

+0

是即使手機被鎖定,它也能工作。通過閱讀此更多信息http://www.vogella.com/articles/AndroidServices/article.html – 2013-03-19 06:24:00

+0

如果你已經回答記得接受答案 – 2013-03-19 06:26:49