gpt4 book ai didi

android - 服务在后台运行?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:46 30 4
gpt4 key购买 nike

我正在构建的应用程序的其中一项功能具有记录功能。我通过在服务中启动一个 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,我可以点击再次按下录制按钮而不是暂停按钮)我应该完成的当然是它继续录制并且我可以看到正在进行的计时器 + 停止按钮。注意:计时器现在不是服务。我应该如何处理这个问题有什么想法吗?

编辑

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

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

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

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

};
};

//编辑

fragment :

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



}

//服务

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



}

最佳答案

首先,您不需要通过某些ActivityManager 方法检查您的Service 是否正在运行。如果您在 onResume() 中调用 startService() && bindService(),Android 足够智能,只要绑定(bind)到 Service 就可以了运行,如果没有,它将创建 Service 并通过其正确记录的生命周期,然后绑定(bind)到它。

你可以在这里做的是:

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

现在,假设您的服务已经在运行并且您想要获得它的正确值。在 ServiceConnection()onServiceConnected() 方法中,您可以在绑定(bind)完成时调用类似 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) {
}
};

现在,您有了指向您的 Service 对象的 myService 变量,您可以在该对象上调用 getters,例如 myService.getTimer()myService.isRecording()

public void initializeUI() {
timerTextview.setText( myService.getTime() );
someOtherUiElement.setText( myService.getSomething() );
if( myService.isRecording() )
recordButton.setImageResource( R.drawable.pause );
} //etc...

顺便说一句,我不知道您是否也在为在退出应用程序时保持服务运行而苦苦挣扎如果这样做,只要 Android 有足够的内存,使用 startService(intent) 将让您的 Service 保持运行。您必须有一段代码可以在其中调用myService.stopService(),否则服务将运行很长时间。

关于android - 服务在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15494917/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com