安卓PubNub服务

15

我已经实现了PubNub订阅和发布代码。我的代码在活动中运行良好。但是现在我想通过Service类将该代码在后台执行。我创建了一个继承IntentService的类,并在onCreate方法中订阅pubnub通道。但是每当我运行应用程序时,服务立即停止,而不显示pubnub状态。我收到以下pubnub错误。我已经链接了所需的pubnub库。

04-09 23:39:32.621: D/Service Message(10033): error[Error: 100-1] : Timeout Occurred

MainActivity.java

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void startService(View v){
        startService(new Intent(this, MyService.class));
    }

    public void stopService(View v){
        stopService(new Intent(this, MyService.class));
    }


}

PubnubHandler.java

public class PubnubHandler{

    public static final String GLOBAL_CHANNEL = "my_channel_name";
    public static final String PUBLISH_KEY = 
            "my_publish_key";
    public static final String SUBSCRIBE_KEY = 
            "my_subscribe_key";
    private Context context;
    private Pubnub pubnub;


    public PubnubHandler(Context context) {

        this.context = context;
        pubnub = new Pubnub(PUBLISH_KEY, SUBSCRIBE_KEY);
        pubnub.setRetryInterval(1000);
    }

    public void notifyUser(String message) {

        final String msg = message;
        Handler handler = new Handler(Looper.getMainLooper());

        handler.post(new Runnable() {

            @Override
            public void run() {

                Toast.makeText(context, msg, 0).show();

            }
        });



    }

    public void subscribe() {

        Callback callback = new Callback() {
            @Override
            public void connectCallback(String channel, Object message) {
                Log.d("Service Message", "Subscribed");
            }

            @Override
            public void disconnectCallback(String channel, Object message) {
                Log.d("Service Message", "Disconnected");
            }

            public void reconnectCallback(String channel, Object message) {
                Log.d("Service Message", "Reconnected");
            }

            @Override
            public void successCallback(String channel, final Object message) {
                Log.d("Service Message", "Message : "+message.toString());
            }

            @Override
            public void errorCallback(String channel, PubnubError error) {
                Log.d("Service Message", "error"+error.toString());
            }
        };

        try {
            pubnub.subscribe(GLOBAL_CHANNEL, callback);
        } catch (PubnubException e) {
            System.out.println(e.toString());
        }
    }

    public void unsubscribe() {
        pubnub.unsubscribe(GLOBAL_CHANNEL);
    }

    public void publish(String message) {

        Callback callback = new Callback() {
            public void successCallback(String channel, Object response) {

            }
            public void errorCallback(String channel, PubnubError error) {

                notifyUser("Something went wrong. Try again.");
            }
        };
        pubnub.publish(GLOBAL_CHANNEL, message , callback);


    }

}

MyService.java

public class MyService extends IntentService {

    public MyService() {
        super("My Service");
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "Service Created", 1).show();
        new PubnubHandler(this).subscribe();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", 1).show();
    }

    @Override
    protected void onHandleIntent(Intent arg0) {

    }
}

清单

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.servicedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MyService" >
        </service>
    </application>

</manifest>

1
嗨,Gaurav。感谢您询问有关在Android中使用PubNub的背景问题。这个问题已经被PubNub员工解决了很多次。您可以发送电子邮件至support@pubnub.com以获取详细信息 :-) - Stephen Blum
1
你能发表答案吗? - Blaasd
2
@PubNub:那为什么不在这里发布答案并帮助未来的访问者避免再次提问呢?如果您已经在另一个问题中这样做了,请将此帖标记为重复。 - Martijn Pieters
这可能会直接回答您的问题,但与PubNub相关的Android服务总体上可能会有所帮助。https://dev59.com/75Pfa4cB1Zd3GeqPDnvL - Craig Conover
1
只是好奇一下,您是否已经联系了PubNub支持。如果还没有,请提供捕获此问题重现的日志文件。您可以使用PubNub调试jar生成日志(https://www.pubnub.com/docs/java-se-java/pubnub-java-sdk-troubleshooting-guide)。如果我们在那里解决了问题,我们将在此发布答案。 - Craig Conover
2个回答

4
你应该总是在IntentServiceonHandleIntent()中完成工作,而不是在onCreate()中。原因是你还没有提供任何代码到onHandleIntent()中,所以IntentService会立即停止。当onHandleIntent()完成并且没有其他startService()调用时,IntentService总是自行关闭。
在你的情况下,调用PubNub API是异步的,因此已经在后台进行了。也许你根本不需要使用IntentService。如果你想创建一个模型对象来保存数据,以便在Activity的配置更改时仍然存在,请考虑使用无界面 Fragment或普通的Service

2
尝试将MyService从简单的Service扩展,而不是IntentServiceIntentService在最后一个任务完成后立即调用stopSelf()。这意味着没有与PubnubHandler相关联的Context,系统可以杀死运行订阅内容的Thread。请保留HTML标签。

1
@Dmide 当然,我理解subscribe是异步调用:https://www.pubnub.com/docs/android-java/pubnub-java-sdk - amukhachov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接