启动IntentService会抛出NullpointerException,并且永远不会调用onHandleIntent()

时间:2017-06-09 18:21:22

标签: java android

这实际上是我在stackoverflow上的第一个问题,我希望我能做到这一点。

我的Broadcastreceiver启动IntentService时遇到了一个非常令人沮丧的问题,因为正如标题所示,startService()会向我抛出NullpointerException,而我在调试时无法找到原因。 stacktrace只是给我引起它的行(由startService()引起)并且我已经在服务中的onHandleIntent()方法中设置了断点,但是从不调用它。

我在android api doc中描述了清单中的接收者和服务。

这是我的两个班级:

public class NetworkBroadcastReceiver extends BroadcastReceiver {

    private static final String LOG_TAG = NetworkBroadcastReceiver.class.getSimpleName();

    @Override
    public void onReceive(final Context context, final Intent intent) {

        ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();

        if (isConnected) {

            try {
                Intent uselessIntent = new Intent();
                IntentService syncService = new SyncService();

                 syncService.startService(uselessIntent);
            }catch (NullPointerException npe){
                npe.printStackTrace(System.err);
            }
        }
    }
}

public class SyncService extends IntentService {

    public SyncService() {
        super(SyncService.class.getSimpleName());
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
            JamDbHelper dbHelper = new JamDbHelper(this);
            Cursor routes = dbHelper.getAllRoutes();

            while (routes.moveToNext()) {

                int synced = routes.getInt(routes.getColumnIndex(DataBaseContract.RouteEntry.COLUMN_SYNC));
                if (synced == 0) {

                    int routeId = routes.getInt(routes.getColumnIndex(DataBaseContract.RouteEntry._ID));
                    int userId = routes.getInt(routes.getColumnIndex(DataBaseContract.RouteEntry.COLUMN_USERID));
                    String startDate = routes.getString(routes.getColumnIndex(DataBaseContract.RouteEntry.COLUMN_STARTDATE));
                    String endDate = routes.getString(routes.getColumnIndex(DataBaseContract.RouteEntry.COLUMN_ENDDATE));

                    Route route = new Route(routeId, userId, startDate, endDate);
                    Cursor coords = dbHelper.getRoute((long) routeId);

                    while (coords.moveToNext()) {

                        double longitude = coords.getDouble(coords.getColumnIndex(DataBaseContract.CoordsEntry.COLUMN_LONG));
                        double latitude = coords.getDouble(coords.getColumnIndex(DataBaseContract.CoordsEntry.COLUMN_LAT));
                        float speed = coords.getFloat(coords.getColumnIndex(DataBaseContract.CoordsEntry.COLUMN_SPEED));
                        int jammed = coords.getInt(coords.getColumnIndex(DataBaseContract.CoordsEntry.COLUMN_JAM));

                        route.putWaypoint(new Waypoint(longitude, latitude, speed, jammed));

                    }

                    Uri basicUri = HttpHandler.buildBasicURI(this);
                    String url = basicUri.toString();

                    String json = new Gson().toJson(route);

                    String enc = "UTF-8";
                    String post_data = null;
                    try {
                        post_data = URLEncoder.encode("api", enc) + "=" + URLEncoder.encode("postRoute", enc) + "&"
                            + URLEncoder.encode("json", enc) + "=" + URLEncoder.encode(json, enc);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    if (HttpHandler.isOnline(this)) {

                        HttpHandler httpHandler = new HttpHandler();
                        String result = httpHandler.makePOSTServiceCall(url, post_data);

                        StateObject state = new Gson().fromJson(result, StateObject.class);

                        if (state.getState().equals(this.getString(R.string.success))) {
                        dbHelper.setSynced(routeId);

                        }
                    }

                }
            }
    }
}

我非常感谢您的帮助,因为这是我的第一个问题,如果您需要更多信息,请立即询问,谢谢!

1 个答案:

答案 0 :(得分:0)

我已更改了正确启动服务的代码。

public class NetworkBroadcastReceiver extends BroadcastReceiver {

    private static final String LOG_TAG = NetworkBroadcastReceiver.class.getSimpleName();

    @Override
    public void onReceive(final Context context, final Intent intent) {

        ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();

        if (isConnected) {

            try {
                Intent uselessIntent = new Intent(context, SyncService.class);
                context.startService(uselessIntent);
            }catch (NullPointerException npe){
                npe.printStackTrace(System.err);
            }
        }
    }
}