我正在开发一个在后台运行Accelerometer服务的应用程序。在此Accelerometer服务中,我从服务器获取数据。但该应用程序在手机上运行良好,但它不适用于Android TV Box。 这是代码
public class AccelerometerService extends Service implements
SensorEventListener
{
public IBinder onBind(Intent intent)
{
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
boolean loading_data=false;
public void onCreate()
{
screenLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
//((( Hanlder Class RUN after 1 Seocond. Update Time/Date )))))
final Handler someHandler = new Handler(getMainLooper());
someHandler.postDelayed(new Runnable()
{
@SuppressWarnings("deprecation")
@Override
public void run()
{
someHandler.postDelayed(this, 2000);
// total_sec_count=obj.Get_Count_Val();
// total_sec_count+=2;
//obj.Set_Screen_count(total_sec_count);
// showtoast("ddd = "+total_sec_count);
// Log.e("count val = ",""+total_sec_count);
// showtoast(("lat/long = "+SingletonClass.getInstance().Get_Latitude()+":"+SingletonClass.getInstance().Get_Longitude()));
}
}, 2000);
}
public void TunrOnWifi()
{
WifiManager wifiManager =
(WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
showtoast("Wifi Tunred On");
}
public void onSensorChanged(SensorEvent event)
{
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
double acceleration = Math.sqrt(Math.pow(x, 2) +
Math.pow(y, 2) +
Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;
/// Log.e("mySensor", "Acceleration is " + acceleration + "m/s^2");
if (acceleration > SHAKE_THRESHOLD)
{
mLastShakeTime = curTime;
Log.e("this", "FALL DETECTED");
}
if(networkobj.Check_Network_Status()==false)
TunrOnWifi();
if(!db.Get_User_Info().get(3).equalsIgnoreCase("NoEmail"))
{
if(loading_data==false)
{
Log.e("Loading DATA STARTED......",""+status+" "+email);
loading_data=true;
SigninAccount();
}
}
// Log.e("Accelertion is = ",""+acceleration + "m/s^2");
if(db.GetAppStatus().equalsIgnoreCase("approved"))
{
//Log.e("APP IS Approved = ",""+acceleration + "m/s^2"+" "+email);
}
else
{
//Log.e("APP is not Approved = ",""+acceleration + "m/s^2 "+email);
//if(!db.Get_User_Info().get(3).equalsIgnoreCase("NoEmail"))
Move_App_Back_to_ForeGround();
}
}
}
} // EOF Onsensor已更改
public int onStartCommand(Intent intent,int flags,int startId) { Log.e(" this"," Start Detecting"); SM =(SensorManager)getSystemService(SENSOR_SERVICE); mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); SM.registerListener(this,mySensor,SensorManager.SENSOR_DELAY_NORMAL);
//here u should make your service foreground so it will keep working even if app closed
return Service.START_STICKY;
}
@覆盖 public void onAccuracyChanged(Sensor arg0,int arg1){ // TODO自动生成的方法存根
}
public void showtoast(String str)
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
//((( Move App To Screen from Background ))))
public void Move_App_Back_to_ForeGround()
{
boolean foregroud=false;
try
{
foregroud = new ForegroundCheckTask().execute(getApplicationContext()).get();
} catch (InterruptedException e)
{ e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
if(!foregroud)
{
//Open Activity IF it is in Background...
Intent it = new Intent("intent.my.action");
it.setComponent(new ComponentName(this.getPackageName(),LoginActivity.class.getName()));
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
this.getApplicationContext().startActivity(it);
}
}
class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {
@Override
protected Boolean doInBackground(Context... params) {
final Context context = params[0].getApplicationContext();
return isAppOnForeground(context);
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}
public void SigninAccount()
{
ArrayList<String>data=new ArrayList<String>();
data=db.Get_User_Info();
name=db.Get_User_Info().get(1);
password=db.Get_User_Info().get(2);
email=db.Get_User_Info().get(3);
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>()
{
String message="Nothing happend";
@Override
protected String doInBackground(Void... params)
{
InputStream is=null;
String result=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email",email));
try{
HttpClient httpclient = new DefaultHttpClient();//("http://employeetrackersystem.comule.com/signin.php");/
HttpPost httppost = new HttpPost("http://pir.alphasols.com/Android_SmartTV_App/login_in_background.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
//Now get the response of the Registeration of new User
try {
if (entity != null) {
InputStream instream = is;//entity.getContent();
String result1= convertStreamToString(instream); //calling function
// Log.e("result",""+result1.toString());
JSONArray arr = new JSONArray(result1);
name=arr.getJSONObject(0).getString("1");
status=arr.getJSONObject(1).getString("1");
message=name;
instream.close();
}
} catch (Exception e)
{
message="Error occured";//: "+e.toString();
}
}
catch(Exception e)
{
message="Error occured";
}
return null;
} protected void onPostExecute(String token)
{
// showtoast("message = "+message);
loading_data=false;
if( !(message.equalsIgnoreCase("no_email")))
{
if(!(message.equalsIgnoreCase("Error occured")))
{
obj.set_create_account(name, email, password);
// set user name/email/password
db.DroTable();
db.Add_User(email, password, email);
db.Add_User(name, password, email);
db.DropStatusTable();
db.Add_App_Status(""+status);
// showtoast("Loading done "+status);
}
}
else
{
//showtoast("Not signed in, Email or password is incorrect");
}
} };
task.execute();
}
public boolean Email_Validation(String email)
{
Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
//String email = "xyz@xyzdomain.com";
Matcher matcher = pattern.matcher(email);
boolean matchFound = matcher.matches();
return matchFound;
}
//((((-- Convert the stream from Url to string --)))
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
} // EOF AcclerometerService类
答案 0 :(得分:0)
在初始化传感器对象的位置,您应该检查它是否存在,如果不存在则产生正确的错误:
SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (accelerometer != null)
{
// Device has Accelerometer
}