java - PubNub 的 Android 服务

标签 java android broadcastreceiver android-service pubnub

我已经实现了 PubNub 订阅和发布代码。我的代码在 Activity 上运行良好。但是现在我想在服务类的帮助下在后台执行该代码。我创建了扩展 IntentService 的类。我正在 onCreate 方法中订阅 pubnub channel 。但是每当我运行应用程序服务时,它都会立即停止而不显示 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) {

    }
}

list

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

最佳答案

您应该始终在 IntentServiceonHandleIntent() 中完成工作,而不是在 onCreate() 中完成工作。 IntentService 立即停止的原因是您没有向 onHandleIntent() 提供任何代码。 IntentService 总是在 onHandleIntent() 完成并且没有任何其他 startService() 调用时自行关闭。

但是,在您的情况下,对 PubNub API 的调用是异步的,因此已经在后台发生。也许你在这里根本不需要 IntentService。如果你想创建一个模型对象来保存在 Activity 的配置更改后仍然存在的数据,请考虑使用 headless Fragment或普通的 Service

关于java - PubNub 的 Android 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29545986/

相关文章:

java - 为什么runtime.exec()没有执行。当我给出 sshpass 命令时

java - 映射与 Hibernate 的关系

java - Ping 结果的正则表达式模式匹配

android - Pending Intent 有生命周期吗?

android - BroadcastReceiver 的动态注册与静态注册

java - 将带中断的字符串转换为数组列表

android - StrictMode 的 DEVELOPER_MODE 定义

android - 在 kotlin 中声明单例

android - 错误 : Could not find com. android.tools.build :gradle:3. 4.1

java - 闹钟服务在手机的省电模式下无法工作