试图在后台运行服务

时间:2014-12-06 10:51:12

标签: android android-activity android-service

我刚开始学习如何通过一些代码示例创建简单的Android应用程序。

我拍摄了一个音频捕获代码示例,该示例仅使用了一个Activity并想要为其添加服务。这样用户将从视图中单击一个按钮,然后活动将开始/停止录音服务。

目标是用户将进入应用程序,单击“开始”按钮,然后服务将启动并将永久保留在后台,直到他返回应用程序并单击“停止”。

问题是,每当我离开应用并打开“最近的应用”并滑出我的应用时,我都会因某种原因看到Congrats! MyService CreatedMy Service Started消息。当我将它从最近的应用程序菜单中滑出时,我不确定为什么要重新启动该服务,我希望它能够继续运行或关闭..

record.java(活动):

package com.example.recordtocloud;
import java.io.File;
import java.io.IOException;

import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;

import android.app.Activity;
import android.os.Bundle;

public class record extends Activity {
    /**
     * Called when the activity is first created.
     */

    private Button start,stop,play;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        start = (Button)findViewById(R.id.button1);
        stop = (Button)findViewById(R.id.button2);
        play = (Button)findViewById(R.id.button3);

        //stop.setEnabled(false);
        //play.setEnabled(false);

    }

    public void start(View view){
        startService(new Intent(this, recordbg.class));

        //start.setEnabled(false);
        //stop.setEnabled(true);
        //Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();

    }

    public void stop(View view){
        stopService(new Intent(this, recordbg.class));

        //stop.setEnabled(false);
        //play.setEnabled(true);
        //Toast.makeText(getApplicationContext(), "Audio recorded successfully",
                //Toast.LENGTH_LONG).show();
    }

    public void play(View view) throws IllegalArgumentException,
            SecurityException, IllegalStateException, IOException{

        MediaPlayer m = new MediaPlayer();
        m.setDataSource(Environment.getExternalStorageDirectory().
                getAbsolutePath() + "/myrecording.3gp");
        m.prepare();
        m.start();
        Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();

    }
}

recordbg.java(服务):

package com.example.recordtocloud;

import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.widget.Toast;
import android.util.Log;

import java.io.IOException;

public class recordbg extends Service {
    private MediaRecorder myAudioRecorder;
    private String outputFile = null;
    private static final String TAG = "recordbg";

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

    @Override
    public void onCreate() {
        Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");

        outputFile = Environment.getExternalStorageDirectory().
                getAbsolutePath() + "/myrecording.3gp";

        myAudioRecorder = new MediaRecorder();
        myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        myAudioRecorder.setOutputFile(outputFile);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
        try {
            myAudioRecorder.prepare();
            myAudioRecorder.start();

        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
        myAudioRecorder.stop();
        myAudioRecorder.release();
        myAudioRecorder  = null;
    }
}

1 个答案:

答案 0 :(得分:0)

A"永远"后台服务在Android中不存在有两个原因:

  1. 没有唤醒锁,cpu可以深度睡眠;
  2. 操作系统可以随时终止您的进程。
  3. 对于第1点,您可以抓住唤醒锁以保持CPU清醒。对于第2点,您可以创建前台服务。操作系统可以杀死前台服务,但概率非常低。

    修改 更新代码,因为您必须实现onStartCommand()而不是onStart(),请参阅here