在服务中创建线程。执行线程后,我需要创建一个活动。不知道如何从后台线程开始活动

问题描述 投票:0回答:1

我有服务。该服务在完成时启动另一个线程,我需要启动另一个名为MapPage.class的新片段活动,该活动显示谷歌地图。该线程从包含GPS坐标的服务器获取json。我将这些坐标保存在单例课程中。因此,在线程完成后,我需要使用单例类中的数据启动MapPagefragmentactivity。

我不知道如何从后台线程启动MapPage.class。我已经从主要活动中看到了使用处理程序的示例,但是我不确定如何将其应用于我的问题。我能找到的最接近的答案是this.

我想知道创建处理程序是否是我唯一的选择?如果还有其他选择?在应用程序类中使用处理程序是否适合解决我的问题?

我的服务类别:

     public class TrackingService extends Service {
    private class MyLocationListener implements LocationListener {
        private final Context context;

        public MyLocationListener(Context context) {
            this.context = context;
        }

        @Override
        public void onLocationChanged(Location location) {
            double latitude = location.getLatitude();
            double longtude = location.getLongitude();
            double altitude = location.getAltitude();
            double accuracy = location.getAccuracy();
            float bearing = location.getBearing();
            String provider = location.getProvider();
            Cood cood = new Cood(latitude, longtude, altitude, accuracy,
                    new Date().getTime(), bearing, provider);

            LocationInformation.getInstanceof().getMapPoint().getCood()
                    .add(cood);

            int size = LocationInformation.getInstanceof().getMapPoint()
                    .getCood().size();

            mBuilder.setContentTitle("GPS Tracker - " + size + "/"
                    + SystemSettings.getInstanceOf().getSize());
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(1, mBuilder.build());

            if (size >= SystemSettings.getInstanceOf().getSize()) {
                Toast.makeText(context, "before creating new thread for Track",
                        Toast.LENGTH_SHORT).show();
                new Thread(new Track(context)).start();
                Toast.makeText(context, "after creating new thread for Track",
                        Toast.LENGTH_SHORT).show();

            }
        }

        @Override
        public void onProviderDisabled(String provider) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }

    LocationManager manag;
    LocationListener locationListener;
    private Context context;
    private Long frequency;
    private Integer minDistance;
    private String deviceRegNo;
    private Integer pointCount;
    private Boolean mode;
    private Builder mBuilder;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }

    @Override
    public IBinder onBind(Intent arg0) {

        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    @Override
    public boolean onUnbind(Intent intent) {

        return super.onUnbind(intent);
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {

    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();

    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent == null) {

            return Service.START_STICKY;
        }

        manag = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);

        locationListener = new MyLocationListener(context);

        frequency = (Long) intent.getExtras().get("frequency");
        minDistance = (Integer) intent.getExtras().get("minDistance");
        deviceRegNo = (String) intent.getExtras().get("deviceRegNo");
        pointCount = (Integer) intent.getExtras().get("pointCount");
        mode = (Boolean) intent.getExtras().get("prodMode");

        if (frequency == null) {
            Toast.makeText(context, "frequency null", Toast.LENGTH_SHORT)
                    .show();
            return Service.START_STICKY;
        }

        if (minDistance == null) {

            return Service.START_STICKY;
        }

        if (deviceRegNo == null) {

            return Service.START_STICKY;
        }

        if (pointCount == null) {
            Toast.makeText(context, "pointCount null", Toast.LENGTH_SHORT)
                    .show();
            return Service.START_STICKY;
        }
        if (mode == null) {
            Toast.makeText(context, "mode is null", Toast.LENGTH_SHORT).show();
            return Service.START_STICKY;
        }

        if (LocationInformation.getInstanceof().getMapPoint().getDevice() == null) {
            Device device = new Device();
            device.setDeviceRegNo(deviceRegNo);
            LocationInformation.getInstanceof().getMapPoint().setDevice(device);
        }

        SystemSettings.getInstanceOf().setSize(pointCount);
        SystemSettings.getInstanceOf().setProdMode(mode);
        Toast.makeText(context, "On the line before pendingIntent statement",
                Toast.LENGTH_SHORT).show();
        Intent resultIntent = new Intent(context, SettingScreen.class);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
                resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        int size = LocationInformation.getInstanceof().getMapPoint().getCood()
                .size();

        mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("GPS Tracker - " + size + "/" + pointCount)
                .setContentText(
                        LocationInformation.getInstanceof().getMapPoint()
                                .getDevice().getDeviceRegNo())
                .setContentIntent(resultPendingIntent);
        Toast.makeText(context, "On the line after NotificationCompat.builder",
                Toast.LENGTH_SHORT).show();

        Notification notification = mBuilder.build();
        Toast.makeText(context, "On the line after mBuilder.build",
                Toast.LENGTH_SHORT).show();
        startForeground(1, notification);
        Toast.makeText(context, "On the line after startForeground",
                Toast.LENGTH_SHORT).show();

        manag.requestLocationUpdates(LocationManager.GPS_PROVIDER, frequency,
                minDistance, locationListener);
        return Service.START_STICKY;
    }
}

我的线程代码是:

     HttpResponse response = httpClient.execute(httpPost);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        String line = "";
        while ((line = br.readLine()) != null) {
            text += line;
            System.out.println("RESULT: " + line);
        }
        MapCoords.getInstanceof().setMapPoint(
                (gson.fromJson(jsonString, MapCoords.class)).getMapPoint());

我必须在这里开始MapPage Activity。我的MapPage活动代码如下:

        public class MapPage extends FragmentActivity {
    ArrayList<Cood> cd = MapCoords.getInstanceof().getMapPoint().getCood();
    Double latitude = cd.get(0).getLatitude();
    Double longitude = cd.get(0).getLongitude();
    LatLng point1;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.basic_demo);
        Toast.makeText(this, "Entered MapPage Activity", Toast.LENGTH_LONG)
                .show();
        setUpMapIfNeeded();

    }

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

    private void setUpMapIfNeeded() {

        if (mMap == null) {
            mMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            point1 = new LatLng(latitude, longitude);
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point1, 17));
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        mMap.addMarker(new MarkerOptions()
                .position(point1)
                .title("Point1")
                .snippet("This is the first GPS co-ordinate"));
    }

}
android handler background-thread
1个回答
2
投票

您可以从任何地方开始活动。您可能必须向您的意图添加一个new_task标志。

    Intent intent = new Intent(context, MapPage.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent); 

如果后台线程在服务内部,则可以将your_service_class.this作为上下文。否则,如果上下文是非活动类或非服务类,则必须将上下文传递给后台线程。

© www.soinside.com 2019 - 2024. All rights reserved.