0

我有一个将 webview 作为服务运行的应用程序,因此音频可以在屏幕锁定时继续播放。该应用程序适用于播客等音频流。但我也希望它适用于 Flash 视频。我可以在 webview 中加载 flash 视频流并让它流畅稳定地播放,但是一旦屏幕关闭或被锁定,音频就会变得断断续续。在 3g 和 WiFi 上的行为是相同的。我尝试使用帖子建议使用唤醒锁:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Tag"); 
wl.acquire();
//do what you need to do
wl.release(); 

但是,这没有效果。我不确定将它放在我的代码中的确切位置,但我已将它放在服务的 oncreate 中,这没有任何效果,我将它放在我的主要活动的 oncreate 中,结果相同。

但是后来在帖子中提出问题的人说WIFI_MODE_FULL_HIGH_PERF能够解决问题。但正如我所说,我在 3g 上对其进行了测试,当屏幕关闭时音频卡顿。

有什么想法可以阻止这种行为吗?

我也知道这是一个 CPU 密集型和电池消耗型应用程序,但我只是为个人使用而开发它。

这是我的服务的完整代码:

public class MyService extends Service {
    private NotificationManager nm;
    private static boolean isRunning = false;

    ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
    int mValue = 0; // Holds last value set by a client.
    static final int MSG_REGISTER_CLIENT = 1;
    static final int MSG_UNREGISTER_CLIENT = 2;
    static final int MSG_SET_INT_VALUE = 3;
    static final int MSG_SET_STRING_VALUE = 4;
    PowerManager.WakeLock wl;


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

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MyService", "Service Started.");
        showNotification();
        isRunning = true;
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
        wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Tag");
    }
    private void showNotification() {
        nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.service_started);
        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.ic_launcher, text, System.currentTimeMillis());
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        nm.notify(R.string.service_started, notification);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService", "Received start id " + startId + ": " + intent);
        return START_STICKY; // run until explicitly stopped.
    }

    public static boolean isRunning()
    {
        return isRunning;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        nm.cancelAll();
        wl.release();
        nm.cancel(R.string.service_started); // Cancel the persistent notification.
        Log.i("MyService", "Service Stopped.");
        isRunning = false;
    }
}

我的主要代码:

public class MainActivity extends Activity {
    Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
    Messenger mService = null;
    boolean mIsBound;
    WebView mWebView;

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);
            try {
                Message msg = Message.obtain(null, MyService.MSG_REGISTER_CLIENT);
                     mService.send(msg);
            } catch (RemoteException e) {
                // In this case the service has crashed before we could even do anything with it
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
            mService = null;
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStart = (Button)findViewById(R.id.btnStart);
        btnStop = (Button)findViewById(R.id.btnStop);
        btnBind = (Button)findViewById(R.id.btnBind);
        btnUnbind = (Button)findViewById(R.id.btnUnbind);

        btnStart.setOnClickListener(btnStartListener);
        btnStop.setOnClickListener(btnStopListener);
        btnBind.setOnClickListener(btnBindListener);
        CheckIfServiceIsRunning();



        //webview
        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);

        mWebView.getSettings().setPluginsEnabled(true);
        mWebView.loadUrl(url);
        mWebView.setWebViewClient(new HelloWebViewClient());


    }


    private void CheckIfServiceIsRunning() {
        //If the service is running when the activity starts, we want to automatically bind to it.
        if (MyService.isRunning()) {
            doBindService();
        }
    }

    private OnClickListener btnStartListener = new OnClickListener() {
        public void onClick(View v){
            startService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnStopListener = new OnClickListener() {
        public void onClick(View v){
            doUnbindService();
            stopService(new Intent(MainActivity.this, MyService.class));
        }
    };
    private OnClickListener btnBindListener = new OnClickListener() {
        public void onClick(View v){

            doBindService();
        }
    };
    private OnClickListener btnUnbindListener = new OnClickListener() {
        public void onClick(View v){

            doUnbindService();
        }
    };

    void doBindService() {
        bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }
    void doUnbindService() {
        if (mIsBound) {
            // If we have received the service, and hence registered with it, then now is the time to unregister.
            if (mService != null) {
                try {
                    Message msg = Message.obtain(null, MyService.MSG_UNREGISTER_CLIENT);
                    mService.send(msg);
                } catch (RemoteException e) {
                    // There is nothing special we need to do if the service has crashed.
                }
            }
            // Detach our existing connection.
            unbindService(mConnection);
            mIsBound = false;
        }
    }

    private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            doUnbindService();
        } catch (Throwable t) {
            Log.e("MainActivity", "Failed to unbind from the service", t);
        }
    }


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

     }
}
4

1 回答 1

3

从您的描述来看,您似乎过早地释放了 WakeLock。如果您只是将该代码块放在服务的 onCreate 中,那么当您的流代码运行时,您真的没有获得 WakeLock。您必须在后台工作期间获取锁。

我用于这样的服务的模式是:

  1. 在 onCreate 中创建 WakeLock(但不要获取它)
  2. 在 onDestroy 中,如果 WakeLock 被持有,则释放它。(主要是为了安全)
  3. 在启动实际后台工作时,无论是在 onBind 还是 onStartCommand 中,都获取锁。
  4. 完成后台工作后,释放唤醒锁。

问题可能与 WebView 的工作方式有关。也就是说,由于这不是生产代码,您可以尝试通过删除释放来简单地“泄漏”唤醒锁,看看是否有帮助。只需在您的活动开始时创建并获取锁,而无需打扰服务。

该服务并没有真正给你太多。您的代码当前的结构方式仍然存在问题。即使您有服务,您的活动仍然可以在后台被删除,仅仅拥有服务不会阻止这一点。此外,因为 WebView 是一个视图,它确实需要一个 Activity 和视图层次结构。

于 2012-03-30T23:12:13.357 回答