简体   繁体   English

在OnClick android上启动后台服务

[英]Start a background service on OnClick android

I want to make an app in which when start is clicked the phone should detect a free fall and should scream. 我想制作一个应用程序,在该应用程序中,单击“开始”后,手机应会检测到自由落体并发出尖叫声。

Basically, when the user clicks the start button the service should start recording Accelerometer reading and detect a free fall and the phone should scream and when he clicks stop the service should terminate. 基本上,当用户单击“开始”按钮时,该服务应开始记录加速度计读数并检测到自由落体,并且手机应发出尖叫声,当用户单击“停止”时,该服务应终止。

I am having very basic knowledge about coding. 我对编码非常基础的知识。 I have written some codes which i have shared below. 我写了一些下面分享的代码。 But the app is not working please help me correct the codes. 但是该应用无法正常运行,请帮助我更正密码。

This is the Main_Activity.xml 这是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>

This is the Android_Manifest.xml 这是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>

This is the Main_Activity.java 这是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));        
}
}

This is the WatcherService.java 这是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);

}

} }

Please Help 请帮忙

Start background service on button click by following code: 通过以下代码在单击按钮时启动后台服务:

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

    });
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));

        }});

Try This : 尝试这个 :

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));

    }

});

Replace your onclick methods with these ... 用这些替换您的onclick方法...

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

Try making public the click listeners: 尝试公开点击监听器:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM