服务在后台运行?

时间:2013-03-19 08:48:43

标签: android service background

我正在构建的应用程序的一个功能具有记录功能。我是通过在服务中启动MediaRecorder对象来实现的:

Intent intent = new Intent(v.getContext(), RecordService.class);
Messenger messenger = new Messenger(handler);
intent.putExtra("COUNT", basic);
intent.putExtra("MESSENGER", messenger);

v.getContext().startService(intent);

//service

//...
mRecorder = new MediaRecorder();
//...

现在我介绍了一个通知,必须让用户知道录音本身的状态,因为如果你去家里或点击后门按钮,它必须继续录音。因此,如果您点击通知,则会返回应用

这就是我在苦苦挣扎的地方,如果我点击通知,我会回到应用程序,但一切都设置为初始状态(计时器回到00:00:00我可以点击再次记录按钮而不是暂停按钮)我应该完成的当然是继续录制并且我可以看到正在进行的计时器+停止按钮。注意:Timer现在不是服务..任何想法我应该如何处理?

修改

假设我关闭了应用程序,该服务仍在运行。重新打开应用程序(以及最初调用服务的活动)我们可以这样做:

private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) myContext.getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (MyService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

所以我部分地覆盖了这一点,但是,从该服务传递到该活动的变量现在已经消失。我的活动中的处理程序似乎在重新打开该活动后没有启动它?

private Handler handler = new Handler() {
        public void handleMessage(Message message) {

            //..
            Bundle bundle = message.getData();
            fileName = bundle.getString("FILENAME");
            tvFileName.setText(fileName);


            Log.e("Filename", "transfered: " + fileName);

        };
    };

// EDIT

片段:

public class LayoutOne extends Fragment implements OnClickListener {

    //vars
    @Override
    public void onPause() {
        super.onPause();
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }

        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message message) {

            int i = message.arg1;
            Bundle bundle = message.getData();
            fileName = bundle.getString("FILENAME");
            tvFileName.setText(fileName);

            Log.e("Handler", "Succesfully transfered: " + (Integer.toString(i)));
            Log.e("Filename", "Succesfully transfered: " + fileName);
        };
    };

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.bRecord:

            if (mStartRecording) {
                mStartRecording = false;
                Intent intent = new Intent(v.getContext(), RecordService.class);

                Messenger messenger = new Messenger(handler);
                intent.putExtra("MESSENGER", messenger);
                v.getContext().startService(intent);


            } else {
                mRecordButton.setText("Record");
                Intent stopIntent = new Intent(v.getContext(),
                        RecordService.class);

                try {
                    v.getContext().stopService(stopIntent);
                } catch (Exception e) {
                    e.printStackTrace();

                }
                mStartRecording = true;
            }

            break;

        case R.id.bStop:
            Intent stopIntent = new Intent(v.getContext(), RecordService.class);
            v.getContext().stopService(stopIntent);
            break;

        }
    }

    public static Fragment newInstance(Context context) {
        LayoutOne f = new LayoutOne();
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        root = (ViewGroup) inflater.inflate(R.layout.layout_one, null);
        myContext = container.getContext();

        //buttons

        mgr = (NotificationManager) myContext.getSystemService(Context.NOTIFICATION_SERVICE);
        return root;
    }



    public void notifyMe(View v) {
        Notification note = new Notification(R.drawable.ic_launcher,
                getString(R.string.notificationbar), System.currentTimeMillis());
        PendingIntent i = PendingIntent.getActivity(myContext, 0, new Intent(
                myContext, ViewPagerStyle1Activity.class), 0);

        note.setLatestEventInfo(myContext, getString(R.string.app_name),
                getString(R.string.notification), i);
        note.number = ++count;
        note.vibrate = new long[] { 500L, 200L, 200L, 500L };
        note.flags |= Notification.FLAG_AUTO_CANCEL;

        mgr.notify(NOTIFY_ME_ID, note);
    }

    public void clearNotification(View v) {
        mgr.cancel(NOTIFY_ME_ID);
    }

    // /SHARED PREFERENCES SETTINGS///
//…

    private void initiatePopupWindow() {
        //..
    }



    @Override
    public void onResume() {
        super.onResume();
        Intent intent = new Intent(myContext, RecordService.class);
        myContext.startService(intent);
        myContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
             LocalBinder binder = (LocalBinder) service;
                myService = binder.getService();
                //myService.setBound(true);
                initializeUI();

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub

        }
    };

    protected void initializeUI() {
        //..

        }

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        myContext.unbindService(mServiceConnection);
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        myContext.unbindService(mServiceConnection);
    }



}

// SERVICE

public class RecordService extends Service {

    //vars

     public class LocalBinder extends Binder {
            RecordService getService() {
                return RecordService.this;
            }
        }

    @Override
    public void onCreate() {
        Log.i("Oncreate", "Service onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle extras = intent.getExtras();
        if (extras != null) {

            messenger = (Messenger) extras.get("MESSENGER");
            count = Integer.toString(extras.getInt("COUNT"));
            try {
                Message message = new Message();
                int arg = 0;
                message.arg1 = arg;

                mFileNamePass=”test”;
                Bundle bundle = new Bundle();
                bundle.putString("FILENAME", mFileNamePass);
                message.setData(bundle);
                messenger.send(message);
            } catch (android.os.RemoteException e1) {
                Log.w(getClass().getName(), "Exception sending message", e1);
            }
        }
        else {
            Log.i("Extras","Didn't find extras");
        }

        Runnable r = new Runnable() {

            @Override
            public void run() {
                checkIfFolderExists();
                String dateFull = calculateDate();
                mFileName = Environment.getExternalStorageDirectory()
                        .getAbsolutePath();
                mFileName += "test.3gp";

                mRecorder = new MediaRecorder();
                mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                mRecorder.setOutputFile(mFileName);
                mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

                try {
                    mRecorder.prepare();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "prepare() failed");
                }

                mRecorder.start();
                Log.i("Service", "Service running");

            }
        };

        Thread t = new Thread(r);
        t.start();
        return RecordService.START_STICKY;
    }

    @Override
    public void onDestroy() {

        Runnable stopRecord = new Runnable() {

            @Override
            public void run() {
                mRecorder.stop();
                mRecorder.release();
                mRecorder = null;

            }

        };
        Thread stopRecordThread = new Thread(stopRecord);
        stopRecordThread.start();
        Log.i("Service", "Service stopped");
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }



}

1 个答案:

答案 0 :(得分:1)

首先,您无需通过某种Service方法检查ActivityManager是否正在运行。如果您在startService() && bindService()中致电onResume(),那么Android足够聪明,只要它已经在运行就绑定到Service,如果没有,则会创建Service它是正确记录的生命周期,然后绑定到它。

这里你能做的是:

@Override
public void onResume() {
    super.onResume();
    Intent intent = new Intent(this, YourService.class);
    startService(intent);
    bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}

现在,假设您的服务已在运行,并且您希望获得正确的值。在onServiceConnected()的{​​{1}}方法中,您可以在绑定完成后调用ServiceConnection()之类的方法:

initializeUI()

现在,您有private ServiceConnection mServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder) service; myService = binder.getService(); myService.setBound(true); initializeUI(); } public void onServiceDisconnected(ComponentName className) { } }; 变量指向您的myService对象,您可以将其称为Service,例如gettersmyService.getTimer()

myService.isRecording()

顺便说一句,我不知道你是否也在努力让你的服务在退出应用程序时保持运行 如果您这样做,只要Android有足够的内存,使用public void initializeUI() { timerTextview.setText( myService.getTime() ); someOtherUiElement.setText( myService.getSomething() ); if( myService.isRecording() ) recordButton.setImageResource( R.drawable.pause ); } //etc... 将使startService(intent)保持运行状态。您必须有一段代码,您可以在其中调用Service,否则,服务将会运行很长时间。