Remote Service läuft nicht im Hintergrund weiter!

  • 0 Antworten
  • Letztes Antwortdatum
E

etnur

Neues Mitglied
0
Hallo zusammen, ich bin neu hier und auch neu bei der App Programmierung unter Java. Ich habe bisher hauptsächlich unter VB.NET und VBA gearbeitet, habe also schon Erfahrungen sammeln können.

Für das was ich mit dieser App realisieren möchte benötige ich einen Hintergrundprozess mit dem ich die Sensoren aufzeichen möchte (Datenlogger). Ich habe nun ein Beispiel gefunden und rumexperimentiert, es funktioniert soweit einwandfrei, aber wenn das Smartphone einschläft hört der Remoteprozess auch auf.
Wie kann ich das ändern?

Es wäre total klasse wenn mir jemand auf die Sprünge helfen könnte.

Wenn ihr noch Informationen benötigt liefere ich diese natürlich.

Vielen Dank vom Frank ;-)).

Hier mal die drei wichtigsten Dateien.
Das Manifest
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.collabera.labs.sai"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".RemoteServiceClient"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>      
            <service android:name="com.collabera.labs.sai.RemoteService" android:process=":remote">
               <intent-filter>
                <action android:name="com.collabera.labs.sai.IMyRemoteService" />
               </intent-filter>
        </service>
        
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest>
Der Remoteservice:
Code:
package com.collabera.labs.sai;

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.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class RemoteService extends Service implements SensorEventListener{
    
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private Handler serviceHandler;
    private int Angle;
    private int MaxAngleRight;
    private int MaxAngleLeft;
    //private string Angles;
    private Task myTask = new Task();
    
    public void SensorActivity() {
    }
    @Override
    public IBinder onBind(Intent arg0) {
        Log.d(getClass().getSimpleName(), "onBind()");
        return myRemoteServiceStub;
    }

    private IMyRemoteService.Stub myRemoteServiceStub = new IMyRemoteService.Stub() {
        public int getAngle() throws RemoteException {
            return Angle;
        }

        @Override
        public int getMaxAngleRight() throws RemoteException {
            // TODO Auto-generated method stub
            return MaxAngleRight;
        }

        @Override
        public int getMaxAngleLeft() throws RemoteException {
            // TODO Auto-generated method stub
            return MaxAngleLeft;
        }
    };
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(getClass().getSimpleName(),"onCreate()");
        }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        serviceHandler.removeCallbacks(myTask);
        serviceHandler = null;
        Log.d(getClass().getSimpleName(),"onDestroy()");
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        MaxAngleRight=0;
        MaxAngleLeft=0;                
        serviceHandler = new Handler();
        serviceHandler.postDelayed(myTask, 1000L);
        mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        mAccelerometer= mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        Log.d(getClass().getSimpleName(), "onStart()");
    }
    
    class Task implements Runnable {
        public void run() {
                serviceHandler.postDelayed(this,1000L);
                
            Log.i(getClass().getSimpleName(), "Incrementing counter in the run method");
        }
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void onSensorChanged(SensorEvent arg0) {
        // TODO Auto-generated method stub
        //counter=arg0.timestamp;
        Angle=(int) arg0.values[2];
        
        if (Angle *-1 > MaxAngleRight){
            MaxAngleRight=Angle*-1;
        }
        
        if (Angle > MaxAngleLeft){
            MaxAngleLeft=Angle;
        }
            
    }
}
Die Activity:
Code:
package com.collabera.labs.sai;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class RemoteServiceClient extends Activity {
    
    private IMyRemoteService remoteService;
    private boolean started = false;
    private RemoteServiceConnection conn = null;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.remoteserviceclient);
        
        Button start = (Button)findViewById(R.id.startButton);
        Button stop = (Button)findViewById(R.id.stopButton);
        Button bind = (Button)findViewById(R.id.bindButton);
        Button release = (Button)findViewById(R.id.releaseButton);
        Button invoke = (Button)findViewById(R.id.invokeButton);
        
        start.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                startService();
            }
        });
        
        stop.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                stopService();
            }
        });       
        
        bind.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                bindService();
            }
        });  
        
        release.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                releaseService();
            }
        });          
        
        invoke.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                invokeService();
            }
        });          

   
    }
    
    private void startService(){
               if (started) {
                   Toast.makeText(RemoteServiceClient.this, "Service already started", Toast.LENGTH_SHORT).show();
               } else {
                   Intent i = new Intent();
                   i.setClassName("com.collabera.labs.sai", "com.collabera.labs.sai.RemoteService");
                   startService(i);
                   started = true;
                   updateServiceStatus();
                   Log.d( getClass().getSimpleName(), "startService()" );
               }
               
    }
       
    private void stopService() {
              if (!started) {
                   Toast.makeText(RemoteServiceClient.this, "Service not yet started", Toast.LENGTH_SHORT).show();
              } else {
                   Intent i = new Intent();
                   i.setClassName("com.collabera.labs.sai", "com.collabera.labs.sai.RemoteService");
                   stopService(i);
                   started = false;
                   updateServiceStatus();
                   Log.d( getClass().getSimpleName(), "stopService()" );
              }
    }
      
    private void bindService() {
                if(conn == null) {
                    conn = new RemoteServiceConnection();
                    Intent i = new Intent();
                    i.setClassName("com.collabera.labs.sai", "com.collabera.labs.sai.RemoteService");
                    bindService(i, conn, Context.BIND_AUTO_CREATE);
                    updateServiceStatus();
                    Log.d( getClass().getSimpleName(), "bindService()" );
                } else {
                    Toast.makeText(RemoteServiceClient.this, "Cannot bind - service already bound", Toast.LENGTH_SHORT).show();
                }
    }
        
    private void releaseService() {
                if(conn != null) {
                    unbindService(conn);
                    conn = null;
                    updateServiceStatus();
                    Log.d( getClass().getSimpleName(), "releaseService()" );
                } else {
                    Toast.makeText(RemoteServiceClient.this, "Cannot unbind - service not bound", Toast.LENGTH_SHORT).show();
                }
    }
        
    private void invokeService() {
                if(conn == null) {
                    Toast.makeText(RemoteServiceClient.this, "Cannot invoke - service not bound", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        int AkAngle = remoteService.getAngle();
                        int MaxAngleRight = remoteService.getMaxAngleRight();
                        int MaxAngleLeft = remoteService.getMaxAngleLeft();
                        String Angles = "Aktuell:"+Integer.toString(AkAngle)+" Max Links:"+Integer.toString(MaxAngleLeft)+" Max Rechts:"+Integer.toString(MaxAngleRight);
                        
                          TextView t = (TextView)findViewById(R.id.notApplicable);
                          t.setText(Angles );
                          Log.d( getClass().getSimpleName(), "invokeService()" );
                    } catch (RemoteException re) {
                        Log.e( getClass().getSimpleName(), "RemoteException" );
                    }
                }
           }                

      
      class RemoteServiceConnection implements ServiceConnection {
          public void onServiceConnected(ComponentName className, 
              IBinder boundService ) {
            remoteService = IMyRemoteService.Stub.asInterface((IBinder)boundService);
            Log.d( getClass().getSimpleName(), "onServiceConnected()" );
          }

          public void onServiceDisconnected(ComponentName className) {
            remoteService = null;
             updateServiceStatus();
             Log.d( getClass().getSimpleName(), "onServiceDisconnected" );
          }
      };
      
      private void updateServiceStatus() {
          String bindStatus = conn == null ? "unbound" : "bound";
          String startStatus = started ? "started" : "not started";
          String statusText = "Service status: "+
                                bindStatus+
                                ","+
                                startStatus;
          TextView t = (TextView)findViewById( R.id.serviceStatus);
          t.setText( statusText );      
        }
      
      protected void onDestroy() {
          super.onDestroy();
          releaseService();
          Log.d( getClass().getSimpleName(), "onDestroy()" );
      }
      
}
 

Ähnliche Themen

AnnaBauer21
Antworten
14
Aufrufe
1.155
AnnaBauer21
AnnaBauer21
Zurück
Oben Unten