Acceleromter服务在Android电视盒上不起作用
我正在开发一个在后台运行加速计服务的应用程序。在这个加速计服务中,我从服务器获取数据。但该应用程序在手机上运行良好,但在Android电视盒上不起作用。 这是密码Acceleromter服务在Android电视盒上不起作用,android,service,accelerometer,Android,Service,Accelerometer,我正在开发一个在后台运行加速计服务的应用程序。在这个加速计服务中,我从服务器获取数据。但该应用程序在手机上运行良好,但在Android电视盒上不起作用。 这是密码 public class AccelerometerService extends Service implements SensorEventListener { public IBinder onBind(Intent intent) { // TODO: Return the communicati
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);
}
}//EOF传感器已更改
公共int onStartCommand(Intent Intent、int标志、int startId)
{
Log.e(“此”,“开始检测”);
SM=(传感器管理器)getSystemService(传感器服务);
mySensor=SM.getDefaultSensor(传感器类型\加速计);
SM.registerListener(此、mySensor、SensorManager.SENSOR\u延迟\u正常)
}
@凌驾
已更改准确性上的公共无效信息(传感器arg0、内部arg1){
//TODO自动生成的方法存根
}
public void showtoos(字符串str)
{
Toast.makeText(this,str,Toast.LENGTH_LONG).show();
}
//((将应用程序从后台移动到屏幕)))
公共无效移动\u应用程序\u返回\u到\u前台()
{
布尔foreground=false;
尝试
{
foreground=newforegroundchecktask().execute(getApplicationContext()).get();
}捕捉(中断异常e)
{e.printStackTrace();
}
捕获(执行例外)
{
e、 printStackTrace();
}
如果(!foreground)
{
//如果活动位于后台,请打开它。。。
Intent it=新的意图(“Intent.my.action”);
it.setComponent(新组件名(this.getPackageName(),LoginActivity.class.getName());
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
this.getApplicationContext().startActivity(it);
}
}
类ForegroundCheckTask扩展了AsyncTask{
@凌驾
受保护的布尔doInBackground(上下文…参数){
最终上下文=参数[0]。getApplicationContext();
返回isAppOnForeground(上下文);
}
专用布尔值isAppOnForeground(上下文){
ActivityManager ActivityManager=(ActivityManager)context.getSystemService(context.ACTIVITY_服务);
List appProcesses=activityManager.getRunningAppProcesses();
if(appprocesss==null){
返回false;
}
最后一个字符串packageName=context.getPackageName();
for(运行AppProcessInfo appProcess:AppProcesss){
if(appProcess.importance==RunningAppProcessInfo.importance\u前台和&appProcess.processName.equals(packageName)){
返回true;
}
}
返回false;
}
}
公共无效签名计数()
{
ArrayListdata=新的ArrayList();
data=db.Get_User_Info();
name=db.Get\u User\u Info().Get(1);
password=db.Get\u User\u Info().Get(2);
email=db.Get\u User\u Info().Get(3);
AsyncTask任务=新建AsyncTask()
{
String message=“没有发生任何事情”;
@凌驾
受保护字符串doInBackground(无效…参数)
{
InputStream=null;
字符串结果=null;
ArrayList nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“email”,email));
试一试{
HttpClient HttpClient=新的默认HttpClient();/(“http://employeetrackersystem.comule.com/signin.php");/
HttpPost HttpPost=新的HttpPost(“http://pir.alphasols.com/Android_SmartTV_App/login_in_background.php");
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
is=entity.getContent();
//现在获取新用户注册的响应
试一试{
如果(实体!=null){
InputStream instream=is;//entity.getContent();
String result1=convertStreamToString(流内);//调用函数
//Log.e(“result”,“”+result1.toString());
JSONArray arr=新JSONArray(结果1);
name=arr.getJSONObject(0.getString(“1”);
status=arr.getJSONObject(1).getString(“1”);
消息=名称;
流内关闭();
}
}捕获(例外e)
{
message=“出错”;/:“+e.toString();
}
}
捕获(例外e)
{
message=“发生错误”;
}
返回null;
}受保护的void onPostExecute(字符串标记)
{
//showtoast(“message=”+message);
加载_数据=错误;
如果(!(message.equalsIgnoreCase(“无电子邮件”))
{
if(!(message.equalsIgnoreCase(“发生错误”))
{
对象设置创建账户(姓名、电子邮件、密码);
//设置用户名/电子邮件/密码
db.DroTable();
添加用户(电子邮件、密码、电子邮件);
db.添加用户(姓名、密码、电子邮件);
db.DropStatusTable();
db.添加应用程序状态(“+状态);
//showtoast(“加载完成”+状态);
}
}
其他的
{
//showtoast(“未登录,电子邮件或密码不正确”);
}
} };
task.execute();
}
公共布尔电子邮件验证(字符串电子邮件)
{
Pattern=Pattern.compile(“.+@.+\\.[a-z]+”);
//字符串电子邮件=”xyz@xyzdomain.com";
Matcher Matcher=pattern.Matcher(电子邮件);
布尔matchFound=matcher.matches();
返回匹配发现;
}
//((-将流从Url转换为字符串--))
私有静态字符串convertStreamToString(InputStream为){
/*
*要将InputStream转换为字符串,我们使用BufferedReader.readLine()命令
*我们迭代直到BufferedReader返回null,这意味着
*没有更多的数据可读取。每行都将附加到StringBuilder
*并作为字符串返回。
*/
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行)“\n
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();
}
}
}
//here u should make your service foreground so it will keep working even if app closed
return Service.START_STICKY;
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();
}
SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if (accelerometer != null)
{
// Device has Accelerometer
}