-1

我创建了一个切换按钮,用于检查我希望我的 MyServices 类启动其服务...我的主布局文件有 3 个按钮,单击第二个按钮时,我的 UserStatus 活动已启动,并且此活动的切换具有我认为的 startService()启动 MyService,因为显示了我在中间给出的祝酒词。现在我打算在后台进行地理位置检测,但我不知道为什么没有发生地理位置,我使用来自 youtube 的视频做到了


这是用户状态活动

package com.salesforce.samples.templateapp;


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.location.*;
import android.content.Intent;
public class UserStatus extends Activity {

    ToggleButton statusToggle;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_user_status, menu);
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_status);
        statusToggle=(ToggleButton)findViewById(R.id.toggleButton1);

        statusToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked)
                {
                    statusToggle.setTextOn("On");
                    Toast.makeText(getApplicationContext(), "Toggle is on", Toast.LENGTH_LONG).show();
                    startService(new Intent(getBaseContext(), MyServices.class));
                }
                else
                {
                    statusToggle.setTextOff("Off");
                    Toast.makeText(getApplicationContext(), "Toggle is off", Toast.LENGTH_LONG).show();
                    stopService(new Intent(getBaseContext(), MyServices.class));
                }
            }
        });
    }


    }

这是 MyServices 类

package com.salesforce.samples.templateapp;

import java.util.HashMap;

import org.json.JSONArray;

import com.salesforce.androidsdk.app.ForceApp;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MyServices extends Service {
    RestClient client;
    double plat;
    double plong;
    int Two_Min=5*60*1000;

    // TextView infoText;

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

        Toast.makeText(this, "Location Updation has started", Toast.LENGTH_LONG)
                .show();
        detectLocation();
        return START_STICKY;

    }

    private void detectLocation() {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Inside detectlocation()", Toast.LENGTH_SHORT)
                .show();
        LocationManager lm1 = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener ll1 = new MyLocationListetner();
        Log.v("X",
                "Response:After creating lm and ll ");

        lm1.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, Two_Min, ll1);
        Log.v("X",
                "Response:After lm1.requestLocationUpdates ");
        ll1.onLocationChanged(null);
    }

    class MyLocationListetner implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            Log.v("X","Response:inside onLocationChanged ");
            Log.v("X","Response:"+location);
            if (location == null) {
                plat = location.getLatitude();
                plong = location.getLongitude();
                Log.v("X",
                        "Response:Location " + Double.toString(plat)+Double.toString(plong));

                String objectType = "akshayg__User__c";
                String objectId = "a02900000089fK3";
                HashMap<String, Object> fields = new HashMap<String, Object>();
                fields.put("Name", "Ashish");
                // fields.put("akshayg__Donor_Location__Latitude__s",
                // Double.toString(plat));
                // fields.put("akshayg__Donor_Location__Longitude__s",
                // Double.toString(plong));
                RestRequest request = null;

                try {
                    request = RestRequest.getRequestForUpdate(
                            getString(R.string.api_version), objectType,
                            objectId, fields);
                    // Toast.makeText(this, "Location Updation has started",
                    // Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    // printHeader("Could not build update request");
                    printException(e);
                    return;
                }

                client.sendAsync(request, new AsyncRequestCallback() {

                    @Override
                    public void onSuccess(RestRequest request,
                            RestResponse result) {

                        // Toast.makeText(this,
                        // ""+Double.toString(plat)+","+Double.toString(plong),
                        // Toast.LENGTH_LONG).show();

                        try {
                             //Toast.makeText(this, "Location Updated",Toast.LENGTH_LONG).show();

                            Log.v("X",
                                    "Response: " + result.toString());
                            /*JSONArray records = result.asJSONObject()
                                    .getJSONArray("records");
                            for (int i = 0; i < records.length(); i++) {
                                // listAdapter.add(records.getJSONObject(i).getString("Name"));
                                // listAdapter.add(records.getJSONObject(i).getString("akshayg__Phone_Number__c"));
                                // listAdapter.add(records.getJSONObject(i).getString("akshayg__Donor_Location__Latitude__s"));
                                // listAdapter.add(records.getJSONObject(i).getString("akshayg__Donor_Location__Longitude__s"));
                            }*/
                        } catch (Exception e) {
                            onError(e);
                        }
                    }

                    @Override
                    public void onError(Exception exception) {
                        Log.v("X",
                                "Response: " + exception.toString());

                        // Toast.makeText(MainActivity.this,
                        // MainActivity.this.getString(ForceApp.APP.getSalesforceR().stringGenericError(),
                        // exception.toString()),
                        // Toast.LENGTH_LONG).show();
                    }

                });
            }

        }

        private void printException(Exception e) {
            String err = "Error: " + e.getClass().getSimpleName();
            Toast.makeText(getApplicationContext(), err, Toast.LENGTH_LONG)
                    .show();
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub


        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

    }

    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Location Updation has stoped", Toast.LENGTH_LONG)
                .show();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }
}

这是我的日志猫错误我得到..

04-02 23:01:33.375: E/AndroidRuntime(4779): FATAL EXCEPTION: main
04-02 23:01:33.375: E/AndroidRuntime(4779): java.lang.RuntimeException: Unable to start service com.salesforce.samples.templateapp.MyServices@413c8878 with Intent { cmp=com.salesforce.samples.templateapp/.MyServices }: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
04-02 23:01:33.375: E/AndroidRuntime(4779):     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2403)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at android.app.ActivityThread.access$1900(ActivityThread.java:127)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1221)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at android.os.Looper.loop(Looper.java:137)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at android.app.ActivityThread.main(ActivityThread.java:4448)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at java.lang.reflect.Method.invokeNative(Native Method)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at java.lang.reflect.Method.invoke(Method.java:511)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at dalvik.system.NativeStart.main(Native Method)
04-02 23:01:33.375: E/AndroidRuntime(4779): Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
04-02 23:01:33.375: E/AndroidRuntime(4779):     at android.app.ContextImpl.startActivity(ContextImpl.java:877)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at android.content.ContextWrapper.startActivity(ContextWrapper.java:276)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at com.salesforce.samples.templateapp.MyServices.onStartCommand(MyServices.java:43)
04-02 23:01:33.375: E/AndroidRuntime(4779):     at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2386)

控件一直运行到 onLocationChanged() 之后,但没有进入 if...else 条件。是 bcoz m 从服务类发送 NULL 到 onLocationChanged()..?但即使我在 if 条件下检查 location!=null,控件仍然没有通过 if 语句..请给出建议更正...!

4

1 回答 1

0

正如 Abhijit 所说,帮助您解决 LogCat 错误会更容易,因为您给出的错误是 android 始终显示的错误,对于代码中引发的任何异常。

如果我不得不猜测,我会说你的UserStatus活动可能没有在你的清单中声明。

编辑:顺便说一句,确保在您测试的设备上启用了 GPS。您可能希望以他们在 Android 开发者网站上的方式以编程方式验证它,如果未启用,则打开位置设置。在这里查看。

于 2013-03-26T15:38:05.760 回答