在OnClick android上启动后台服务

时间:2018-10-09 05:08:32

标签: java android eclipse

我想制作一个应用程序,单击“开始”后,手机应会检测到自由落体并发出尖叫声。

基本上,当用户单击“开始”按钮时,服务应开始记录加速度计读数并检测到自由落体,并且手机应发出尖叫声,而当用户单击“停止”时,服务应终​​止。

我对编码非常基础的知识。我写了一些下面分享的代码。但是该应用无法正常运行,请帮助我更正密码。

这是Main_Activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/main_status"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/start_button"
        android:layout_marginTop="18dp"
        android:padding="4.0dip"
        android:text="@string/Welcome" 
        android:textStyle="bold"       />

    <Button
        android:id="@+id/start_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="57dp"
        android:onClick="startWatcherService"
        android:text="@string/start" />

    <Button
        android:id="@+id/stop_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="62dp"
        android:text="@string/stop" 
        android:onClick="stopWatcherService"
        />

</RelativeLayout>

这是Android_Manifest.xml

 <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.sitc.fallscream.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.sitc.fallscream.WatcherService"
            android:label="@string/title_activity_watcher_service" >
        </activity>
        <service android:name="com.sitc.fallscream.WatcherService"/>
    </application>

</manifest>

这是Main_Activity.java

public class MainActivity extends Activity {

TextView mMainStatus;
Button mStartButton;


class C01891 implements OnClickListener{
    C01891(){

    }

    public void onClick(View v) {
        Log.i("MainActivity", "Start button clicked.");
        if(WatcherService.g_WatcherIsRunning){
            MainActivity.this.stopWatcherService();
        } else{
            MainActivity.this.startWatcherService();
        }
    }
}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setVolumeControlStream(4);
    this.mStartButton = (Button) findViewById (id.start_button);
    this.mStartButton.setOnClickListener(new C01891());
    this.mMainStatus = (TextView) findViewById(id.main_status);
    IntentFilter filter = new IntentFilter();
    filter.addAction(WatcherService.WATCHER_SERVICE_STATUS_CHANGED);

}


private void startWatcherService() {
    startService(new Intent (this,WatcherService.class));       
}

private void stopWatcherService() {
    sendBroadcast (new Intent(WatcherService.STOP_WATCHER_SERVICE));        
}
}

这是WatcherService.java

public class WatcherService extends Service implements SensorEventListener, OnCompletionListener{

public static final String STOP_WATCHER_SERVICE= "com.sitc.fallscream.STOP_WATCHER_SERVICE"; 
public static final String WATCHER_SERVICE_STATUS_CHANGED = "com.sitc.fallscream.WATCHER_SERVICE_STATUS_CHANGED"; 
public static boolean g_WatcherIsRunning = false;
private final int ACCELEROMETER_REPORTING_PERIOD_US = 50000;
private final int COUNTER_THRESHOLD =3;
private final float SCREAM_THRESHOLD_GS = 0.1f;
private final int WATCHER_SERVICE_NOTIFICATION_ID = 8008135;
private Sensor mAccelerometer;
private AudioManager mAudiomanager;
private int mCounter = 0;
private MediaPlayer mMediaPlayer;
private PowerManager mPowerManager;
private SensorManager mSensorManager;
private boolean mShouldScream = true;
//private OnStopReceiver mStopReceiver;
private WakeLock mWakelock;


@Override
public IBinder onBind(Intent intent) {
    return null;
}


public void onCreate() {
  Log.i("WatcherService", "onCreate");
  IntentFilter filter = new IntentFilter();
  filter.addAction(STOP_WATCHER_SERVICE);
  prepareMediaplayer();
  this.mPowerManager = (PowerManager) getSystemService("power");
  this.mWakelock = this.mPowerManager.newWakeLock(1, "WatcherService");
  this.mWakelock.acquire();
  this.mSensorManager = (SensorManager) getSystemService("sensor");
  this.mAccelerometer = this.mSensorManager.getDefaultSensor(1);
  this.mSensorManager.registerListener(this, this.mAccelerometer, 50000);     
}


public void onSensorChanged(SensorEvent event) {
    float[] values = event.values;
    float x = values[0];
    float y = values[1];
    float z = values[2];
    if (((float) Math.sqrt((double) (((x * x) + (y * y)) + (z * z)))) / 9.8f < 0.1f) {
        this.mCounter++;
        if (this.mCounter >=3) {
            scream();
            return;
        }
        return;
    }
    this.mCounter = 0;
    this.mShouldScream = true;

}


public void onAccuracyChanged(Sensor sensor, int accuracy) {        
}


public void onDestroy() {
    this.mSensorManager.unregisterListener(this, this.mAccelerometer);
    stopForeground(true);
    setStatus(false);
    this.mWakelock.release();
}

private void stopWatcherService() {
    stopSelf();
}


private void setStatus(boolean isRunning) {
    g_WatcherIsRunning = isRunning;
    sendBroadcast(new Intent(WATCHER_SERVICE_STATUS_CHANGED));
}

private void scream() {
    if(!this.mMediaPlayer.isPlaying() && this.mShouldScream){
        Log.i("WatcherService", "Aaaah!");
        this.mShouldScream = false;
        this.mAudiomanager.requestAudioFocus(null, 4, 2);
        this.mMediaPlayer.start();
    }
}


private void prepareMediaplayer() {
    AssetManager assetManager = getAssets();
    this.mMediaPlayer = new MediaPlayer();
    this.mMediaPlayer.setOnCompletionListener(this);
    this.mMediaPlayer.setAudioStreamType(4);
    this.mAudiomanager = (AudioManager) getSystemService("audio");
    try{
        AssetFileDescriptor afd = assetManager.openFd("scream.wav");
        this.mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        afd.close();
        this.mMediaPlayer.prepare();
    } catch (IOException ex){
        ex.printStackTrace();
        stopWatcherService();
    }

}


public void onCompletion(MediaPlayer mp) {
    this.mAudiomanager.abandonAudioFocus(null);

}

}

请帮助

5 个答案:

答案 0 :(得分:0)

通过以下代码在单击按钮时启动后台服务:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent startServiceIntent = new Intent(YourActvity.this, MyBackgroundService.class);
            startService(startServiceIntent);
        }

    });

答案 1 :(得分:0)

start_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startService(new Intent(getApplicationContext(), WatcherService.class));

        }});

stop_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stopService(new Intent(getApplicationContext(), WatcherService.class));

        }});

答案 2 :(得分:0)

尝试:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

      Intent intent = new Intent(MainActivity.this, WatcherService.class);  
      startService(intent);

      // OR
      startService(new Intent(MainActivity.this, WatcherService.class));

    }

});

答案 3 :(得分:0)

用这些替换您的onclick方法...

   private void startWatcherService(View v) {
startService(new Intent (this,WatcherService.class));       
}
private void stopWatcherService(View v) {
sendBroadcast (new Intent(WatcherService.STOP_WATCHER_SERVICE));        
}

答案 4 :(得分:0)

尝试公开点击监听器:

public void startWatcherService() {
    startService(new Intent (this,WatcherService.class));       
}

public void stopWatcherService() {
    sendBroadcast (new Intent(WatcherService.STOP_WATCHER_SERVICE));        
}