Android Service for PubNub

我已经实现了PubNub订阅和发布代码。我的代码在活动上工作正常。但现在我想在服务类的帮助下在后台执行该代码。我已经创建了我的类,扩展了.我正在订阅方法中的pubnub频道。但是,每当我运行时,应用服务都会立即停止,而不会显示 pubnub 状态。我得到以下 pubnub 错误。我也链接了pubnub所需的库。IntentServiceonCreate

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

主要活动.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);


    }

}

我的服务.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

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

但是,在您的情况下,对API的调用是异步的,因此已经在后台发生。也许你根本不需要这里。如果要创建一个模型对象来保留可在 配置更改 中幸存下来的数据,请考虑使用无头 Fragment 或 plain 。PubNubIntentServiceActivityService


答案 2

尝试从 简单 而不是 扩展 。 在最后一个任务完成后进行调用。这意味着不会有关联,系统可以只杀死一个订阅的东西正在运行的地方。MyServiceServiceIntentServiceIntentServicestopSelf()ContextPubnubHandlerThread


推荐