1
我有一個關於由PhoneStateListener啓動時的服務行爲的問題。由PhoneStateListener啓動的服務在完成之前被終止
我的客戶想要一個安全軟件來跟蹤被盜設備。我正在寫的功能會在按下「發送」按鈕時拍照。
所以我寫了一個註冊PhoneStateListener的broadcastreceiver。這位聽衆啓動了一項服務,無需預覽即可從面向相機拍攝照片。問題在於時機。該服務在圖片可用之前正在被殺死!但是爲什麼服務被SO殺死?
通過廣播接收器:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class PhoneReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ATMPhoneStateListener phoneListener=new ATMPhoneStateListener(context);
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
}
}
的PhoneStateListener:
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.content.Context;
import android.content.Intent;
import java.lang.reflect.Method;
import android.os.IBinder;
import android.os.Binder;
import com.my.services.TakePictureService;
public class MyPhoneStateListener extends PhoneStateListener {
private Context context;
public MyPhoneStateListener (Context context) {
this.context = context;
}
public void onCallStateChanged(int state, String incomingNumber){
switch(state)
{
case TelephonyManager.CALL_STATE_IDLE:
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
phoneIsOffHeek();
break;
case TelephonyManager.CALL_STATE_RINGING:
break;
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void phoneIsOffHeek() {
Intent takePictureService = new Intent(context, TakePictureService.class);
context.startService(takePictureService);
}
}
的服務:
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
public class TakePictureService extends Service {
private Context context;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
context = this.getApplicationContext();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if (GBCameraUtil.findFrontFacingCamera() != -1) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmDDhhmmss");
String date = dateFormat.format(new Date());
final String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + ".jpg";
GBTakePictureNoPreview c = new GBTakePictureNoPreview(context, this);
c.setUseFrontCamera(true);
c.setFileName(fileName);
if (c.cameraIsOk()) {
try {
c.takePicture();
} catch (Exception e) {
}
}
} else {
stopSelf();
}
}
的權限都OK,代碼工作有時有有時沒有,因爲該服務被殺害。
任何想法?