如何向项目添加服务?

时间:2017-10-04 11:46:56

标签: android

当我们按下“开始”按钮而不打开相机时,我的应用程序正在录制视频,并且在看到另一个按钮后单击它。 我希望当我们点击“开始”按钮时,它会记录它,但在后台(使用服务),我尝试但我没有成功。 当我点击开始时,我需要在关闭应用程序或转到其他应用程序时继续录制。 谁能告诉我怎么办呢?

我的xml代码:

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textSize="35dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"/>

    <TextView
        android:id="@+id/tvTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="זמן הקלטה: "
        android:textSize="19dp"
        android:layout_below="@id/tvTitle"
        android:layout_marginTop="70px"
        android:layout_alignParentRight="true"/>

    <EditText
        android:id="@+id/etTime"
        android:layout_width="500px"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/tvTime"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/tvMail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="אימייל:"
        android:textSize="19dp"
        android:layout_below="@id/tvTime"
        android:layout_marginTop="70px"
        android:layout_alignParentRight="true"/>

    <EditText
        android:id="@+id/etMail"
        android:layout_width="500px"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/tvMail"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@id/tvMail"/>

    <Button
        android:id="@+id/btnStart"
        android:layout_width="300px"
        android:layout_height="300px"
        android:layout_gravity="center|center"
        android:background="@drawable/button_states"
        android:text="Start"
        android:textSize="25dp"
        android:layout_marginTop="150px"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/tvMail"/>

    <Button
        android:id="@+id/btnSave"
        android:layout_width="55dp"
        android:layout_height="55dp"
        android:layout_gravity="center|center"
        android:layout_marginTop="50px"
        android:background="@drawable/button_states"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="30px"
        android:layout_marginRight="30px"
        android:text=">" />

    <SurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="0.1dp"
        android:layout_height="0.1dp"
        android:layout_gravity="center|center"></SurfaceView>

这是我的代码:

public class VideoCapture extends Activity implements SurfaceHolder.Callback{
public static SurfaceView cameraView;
public static SurfaceHolder holder;
public static Camera mCamera;
public static boolean mPreviewRunning;

private Button btnStart,btnSave; // buttons of the app
private MediaRecorder recorder; // object for recording the videos
private CamcorderProfile cpHigh;
private boolean recording,savingEvidence = false;
private int counter;
private EditText etTime,etMail;
private View view;
private String firstVideo,secondVideo;
private Handler handler;
private File myvideoDirectory;; // file for new directory
private int recordTime;     // time to record in ms
private String savePath;    // string for saving the file in directory

private final int REFRESH_VIDEOS = 1;
private final int SAVE_EVIDENCE  = 2;
/// </Variables>

/// <Getters and Setters functions>
// get the counter
public int getCounter() {
    return counter;
}

// set the counter
public void setCounter(int counter) {
    this.counter = counter;
}
/// </Getters and Setters functions>

/// <Activity's Functions>
@Override
protected void onResume() {
    super.onResume();
}

@Override
protected void onStart() {
    super.onStart();

}
/// </Activity's Functions>
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    // create a File object for the parent directory
    savePath =   "/sdcard/Recorder/";
    myvideoDirectory = new File(savePath);
    // have the object build the directory structure, if needed.
    if (!myvideoDirectory.exists())
    {
        myvideoDirectory.mkdirs();
    }

    setContentView(R.layout.main);
    // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    initHandler();
    // new media recorder object
    recorder = new MediaRecorder();
    // init the medica recorder object
    initRecorder();

    cameraView = (SurfaceView) findViewById(R.id.surfaceView);
    holder = cameraView.getHolder();
    holder.addCallback(this);
    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    //recordTime = 30000;

    // button to record the video
    btnStart = (Button) findViewById(R.id.btnStart); // get the Button object's id
    btnStart.setOnClickListener(new View.OnClickListener()
    {
        @Override
        // recording / stopping the video
        public void onClick(View v)
        {
            /// <Variables>;
            int timeInSeconds;
            InputMethodManager imm;
            /// </Variables>

            if (!recording) // if we are not recording
            {
                try
                {
                    etTime = (EditText)findViewById(R.id.etTime); // get the EdisText of the seconds to record object's id
                    etMail = (EditText)findViewById(R.id.etMail); // get the EditText of the mail to send the video

                    // toast's message to show error message of input error values
                    if(etMail.getText().toString().equals("") && etTime.getText().toString().equals(""))
                        Toast.makeText(getApplicationContext(), "Please write a valid number and email!", Toast.LENGTH_SHORT).show();
                    else
                    {
                        if(etMail.getText().toString().equals(""))
                            Toast.makeText(getApplicationContext(), "Please write a valid email!", Toast.LENGTH_SHORT).show();
                        else
                        {
                            if(etTime.getText().toString().equals(""))
                                Toast.makeText(getApplicationContext(), "Please write a valid number!", Toast.LENGTH_SHORT).show();
                            else
                            {
                                timeInSeconds = Integer.parseInt(etTime.getText().toString()); // parse from text to int
                                recordTime = timeInSeconds * 1000;
                                recording = true; // change the boolen valut to true because we are recording now
                                Toast.makeText(getApplicationContext(), "Recording Started", Toast.LENGTH_SHORT).show();
                                recorder.start(); // start recording
                                btnSave.setVisibility(View.VISIBLE); // enable the button
                                btnStart.setText("Stop"); // set the text to Stop
                                handler.sendEmptyMessageDelayed(REFRESH_VIDEOS, recordTime);
                            }
                        }
                    }

                    // hide the keyboard
                    view = getCurrentFocus();
                    if (view != null)
                    {
                        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    }
                    // create a new intent for Service's object to record in background
                }
                catch (Exception e)
                {
                    // hide the keyboard
                    view = getCurrentFocus();
                    if(view != null)
                    {
                        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(view.getWindowToken(),0);
                    }
                }
            }
            else // if we are already recording
            {
                recording = false; // change the boolen valut to false because we are not recording now
                btnSave.setVisibility(View.GONE); // enable the button
                btnStart.setText("Start"); // set the text to Start
                stopRecording(); // stop recording
            }
        }
    });

    // button to save the video
    btnSave = (Button) findViewById(R.id.btnSave); // get the Button object's id
    btnSave.setVisibility(View.GONE); // disable the button
    btnSave.setOnClickListener(new View.OnClickListener()
    {
        @Override
        // saving the last 30 seconds
        public void onClick(View v)
        {
            savingEvidence = true;// Stop the REFRESH_VIDEOS "thread"
            handler.sendEmptyMessageDelayed(SAVE_EVIDENCE,recordTime); // Stop the current video after recordTime seconds
            // SAVE_EVIDENCE(message) , recordTime(object)
        }
    });

}

/// <Functions>
// init the media recorder object
private void initRecorder()
{
    recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    //recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
    recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

    cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);


    recorder.setProfile(cpHigh); // Set the video output format and encoding
    // create a string for saving the video
    String videoName = savePath + "Record " + getCounter() + ".mp4";
    recorder.setOutputFile(videoName);
    firstVideo = videoName;
    setCounter(++counter); // count the number of the videos

    //recorder.setMaxDuration(5000); // 5 seconds
}

// prepare the recorder before we are recording
private void prepareRecorder() {
    recorder.setPreviewDisplay(holder.getSurface()); // get the surface object

    try
    {
        recorder.prepare(); // prepare the media recorder object , its very important to
        // prepare the object before we are recording
    }
    catch (IllegalStateException e)
    {
        e.printStackTrace();
        finish();
    }
    catch (IOException e)
    {
        e.printStackTrace();
        finish();
    }
}

// init the handler object
public void initHandler()
{
    handler = new Handler(new Handler.Callback()
    {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public boolean handleMessage(Message message)
        {
            switch (message.what)
            {
                case REFRESH_VIDEOS:
                    // Validations
                    if(savingEvidence || !recording)
                    { break; }

                    // Stop the first video
                    recorder.stop(); // stop recording
                    // Show a message for saving the video
                    Toast.makeText(getApplicationContext(), "Video saved! \n" + firstVideo, Toast.LENGTH_SHORT).show();


                    // delete the second video
                    if(secondVideo != null)
                    {
                        File file = new File(secondVideo);
                        file.delete();
                    }

                    // Change the name of the second video to first video
                    secondVideo = firstVideo;

                    // Start new video
                    initRecorder();
                    prepareRecorder();
                    recorder.start(); // start recording

                    // call handler for maximum 10 seconds and stop the video
                    handler.sendEmptyMessageDelayed(REFRESH_VIDEOS,recordTime);
                    break;

                case SAVE_EVIDENCE:
                    // stop the first video
                    //stopRecording(); // stop recording
                    recorder.stop();
                    // Show a message for saving the video's evidence
                    Toast.makeText(getApplicationContext(), "Evidence saved! " + "\n" +firstVideo , Toast.LENGTH_SHORT).show();

                    // move firstvideo and secondvideo to private folder
                    Date dt = new Date(); // get the date
                    int hours = dt.getHours(); // get the hour now
                    int minutes = dt.getMinutes(); // get the minutes now
                    int seconds = dt.getSeconds(); // get the seconds now
                    // get the time
                    String curTime = hours + ":" + minutes + ":" + seconds;
                    // saving the videos with the time and the date
                    String firstPath = savePath + "Evidence - " + curTime+"/";
                    String secondPath = savePath + "Evidence - " + curTime+"/";
                    moveFile(firstVideo, firstPath, "1.mp4");
                    moveFile(secondVideo, secondPath,"2.mp4");
                    firstPath += "1.mp4";
                    secondPath += "2.mp4";

                    // resume REFRESH_VIDEOS
                    handler.sendEmptyMessageDelayed(REFRESH_VIDEOS,recordTime);
                    savingEvidence = false;

                    // creating intent object of SendingEmail class for sending a email
                    String[] TO = {((EditText)findViewById(R.id.etMail)).getText().toString()};
                    Intent emailIntent = new Intent(Intent.ACTION_SEND);
                    emailIntent.setType("vnd.android.cursor.dir/email");
                    emailIntent.putExtra(Intent.EXTRA_EMAIL,TO);
                    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+firstPath));
                    emailIntent.putExtra(Intent.EXTRA_SUBJECT,"Evidence");
                    startActivity(Intent.createChooser(emailIntent,"Send Email..."));

                    // Start new video
                    initRecorder();
                    prepareRecorder();
                    recorder.start(); // start recording
                    break;
            }
            return false;
        }
    });
}

// Stops the recording
private void stopRecording()
{
    // stop new video
    Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
    recorder.stop();
    initRecorder();
    prepareRecorder();
}

// when the surface just created in the first time
public void surfaceCreated(SurfaceHolder holder)
{
    prepareRecorder();
}

// when we want to change a details of the surface object
public void surfaceChanged(SurfaceHolder holder, int format, int width,
                           int height)
{
}

// when the surface object is gonna die
public void surfaceDestroyed(SurfaceHolder holder)
{
    if (recording) // if we are recording
    {
        recorder.stop(); // stop recording
        recording = false;
    }
    recorder.release(); // release the media recorder object , its very important if we want to use again
    finish();
}

// move the files to new directory for saving the video's evidence
private void moveFile(String videoPath, String outputPath, String videoName)
{
    InputStream in = null;
    OutputStream out = null;
    try
    {
        File dir = new File (outputPath);
        // if the directory isn't exist
        if (!dir.exists())
        {
            dir.mkdirs();
        }

        in = new FileInputStream(videoPath);
        out = new FileOutputStream(outputPath + videoName);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;

        // write the output file
        out.flush();
        out.close();
        out = null;

        // delete the second video
        File file = new File(videoPath);
        file.delete();

    }

    catch (FileNotFoundException e1)
    {
        Log.e("tag", e1.getMessage());
    }
    catch (Exception e)
    {
        Log.e("tag", e.getMessage());
    }

}
/// </Functions>

}

1 个答案:

答案 0 :(得分:-1)

如果你想添加服务而不是像你这样在你的包中添加新类,并通过服务扩展

class Test extends Services{
}

现在将其添加到您的Mainefest.xml中并在Activity

中使用此服务

在Test Service类

上添加计时器
    public class TestService extends Service {

    public final String TAG = TestService.this.getClass().getSimpleName();

    // constant
    public static final long NOTIFY_INTERVAL = 10 * 1000; //Call every 10 sec
    // run on another Thread to avoid crash
    private Handler mHandler = new Handler();
    // timer handling
    private Timer mTimer = null;

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

    @Override
    public void onCreate() {
        // cancel if already existed
        if (mTimer != null) {
            mTimer.cancel();
        } else {
            // recreate new
            mTimer = new Timer();
        }
        // schedule task
        mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
    }

    class TimeDisplayTimerTask extends TimerTask {

        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    //Here your Video Recording code which call every 10 sec 
                }

            });
        }
    }

}