按下按钮时,按钮内的服务类不起作用

时间:2014-03-15 21:30:02

标签: android xml button service onclicklistener

当我按下按钮发送时,由于某种原因它没有启动服务 - 它之前正在工作,但现在却没有。 logcat并没有真正提供有关正在发生的事情的任何信息。考虑到以前的工作,这很奇怪。另一个按钮有效,但这个按钮没有 - 我很困惑。

    Logcat:
    03-15 17:14:33.019: D/OpenGLRenderer(21118): Flushing caches (mode 1)
    03-15 17:14:33.339: D/OpenGLRenderer(21118): Flushing caches (mode 0)
    03-15 17:14:33.339: D/memalloc(21118): ion: Unmapping buffer  base:0x52622000       size:2088960
    03-15 17:14:33.339: D/memalloc(21118): ion: Unmapping buffer  base:0x52e21000     size:2088960
    03-15 17:14:33.339: D/memalloc(21118): ion: Unmapping buffer  base:0x5311f000 size:2088960
    03-15 17:14:33.389: W/IInputConnectionWrapper(21118): showStatusIcon on inactive InputConnection
    03-15 17:14:33.389: W/IInputConnectionWrapper(21118): InputConnection = com.android.internal.widget.EditableInputConnection@40dabaf0, active client = false
    03-15 17:17:40.369: I/Adreno200-EGLSUB(21118): <ConfigWindowMatch:2087>: Format RGBA_8888.
    03-15 17:17:40.389: D/memalloc(21118): ion: Mapped buffer base:0x52622000 size:2088960 offset:0 fd:60
    03-15 17:17:40.409: D/memalloc(21118): ion: Mapped buffer base:0x52e21000 size:2088960 offset:0 fd:64
    03-15 17:17:40.429: D/memalloc(21118): ion: Mapped buffer base:0x5311f000 size:2088960 offset:0 fd:67
    03-15 17:17:41.981: I/System.out(21118): inside the setServiceAlarm
    03-15 17:17:42.001: D/memalloc(21118): ion: Mapped buffer base:0x52dac000 size:98304 offset:0 fd:70
    03-15 17:17:43.502: I/System.out(21118): inside the setServiceAlarm
    03-15 17:17:45.494: D/memalloc(21118): ion: Unmapping buffer  base:0x52dac000 size:98304
    03-15 17:17:45.544: D/memalloc(21118): ion: Mapped buffer base:0x52dac000 size:98304 offset:0 fd:70
    03-15 17:17:48.988: D/memalloc(21118): ion: Unmapping buffer  base:0x52dac000 size:98304
    03-15 17:17:54.174: I/System.out(21118): inside the setServiceAlarm
    03-15 17:17:54.204: D/memalloc(21118): ion: Mapped buffer base:0x52dac000 size:98304 offset:0 fd:70
    03-15 17:17:57.677: D/memalloc(21118): ion: Unmapping buffer  base:0x52dac000 size:98304

清单文件:              

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />

      <permission 
        android:name="com.example.gmapsapp.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
        <uses-permission android:name="android.permission.SEND_SMS" />
        <uses-permission android:name="android.permission.WRITE_SMS" />
        <uses-permission android:name="android.permission.READ_SMS" />
        <uses-permission android:name="com.example.gmapsapp.permission.MAPS_RECEIVE"/>
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
        <uses-permission android:name="android.permission.VIBRATE" />
        <uses-permission 
            android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

        <uses-feature 
            android:glEsVersion="0x00020000"
            android:required="true"/>

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo" >
        <activity
            android:name="com.example.whereyouapp.ControllerTestingScreen"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.whereyouapp.MainScreen"
            android:label="@string/app_name" >
                <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.whereyouapp.MainSplashScreen" />
        </activity>
        <activity
            android:name="com.example.whereyouapp.AddRouteScreen"
            android:label="@string/title_activity_add_route_screen"
            android:parentActivityName="com.example.whereyouapp.MainScreen" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.whereyouapp.MainScreen" />
        </activity>
        <activity
            android:name="com.example.whereyouapp.SavedRoutesScreen"
            android:label="@string/title_activity_credits_screen"
            android:parentActivityName="com.example.whereyouapp.MainScreen" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.whereyouapp.MainScreen" />
        </activity>
        <activity
            android:name="com.example.whereyouapp.TutorialScreen"
            android:label="@string/title_activity_tutorial_screen"
            android:parentActivityName="com.example.whereyouapp.MainScreen" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.whereyouapp.MainScreen" />
        </activity>
        <activity
            android:name="com.example.whereyouapp.SettingsScreen"
            android:label="@string/title_activity_settings_screen"
            android:parentActivityName="com.example.whereyouapp.MainScreen" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.whereyouapp.MainScreen" />
        </activity>
        <activity
            android:name="com.example.whereyouapp.AddRouteScreenMessage"
            android:label="@string/title_activity_add_route_screen_message"
            android:parentActivityName="com.example.whereyouapp.AddRouteScreen" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.whereyouapp.AddRouteScreen" />
        </activity>
         <activity
            android:name="com.example.whereyouapp.SetAddressScreen"
            android:label="Set Address"
            android:parentActivityName="com.example.whereyouapp.AddRouteScreen" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.whereyouapp.AddRouteScreen" />
        </activity>
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyDxDrvWoRS6mR6FQayfSVQ0oOIz1WOc7mw"/>
        <meta-data android:name="com.google.android.gms.version" android:value="4132500" />
    </application>
</manifest>

测试屏幕:

    //This class wil be used to test controller functions, it will consist of a screen with   buttons that do various functions
    package com.example.whereyouapp;

    import android.net.Uri;
    import android.os.Bundle;
    import android.app.Activity;
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.support.v4.app.NotificationCompat;
    import android.support.v4.app.TaskStackBuilder;
    import android.telephony.SmsManager;
    import android.view.Menu;
    import android.view.View.OnClickListener;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.content.ContentValues;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.PorterDuff;
    import android.view.View;
    import android.widget.Button;

    public class ControllerTestingScreen extends Activity{

    public static Context c;
    protected void onCreate(Bundle savedInstanceState) {

        c=this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_controller_test_screen);

        Button button = (Button) findViewById(R.id.testbutton);
        button.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
        OnClickListener buttonListener = new View.OnClickListener(){
            public void onClick(View arg0) {
                Toast.makeText(getBaseContext(), "inside the onclick", Toast.LENGTH_LONG).show();
                Controller.setServiceAlarm(getBaseContext(), true);
            }

        };
        button.setOnClickListener(buttonListener);

        Button notibutton = (Button) findViewById(R.id.notificationbutton);
        notibutton.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
        OnClickListener nbuttonListener = new View.OnClickListener(){
            public void onClick(View arg0){
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getBaseContext());
                mBuilder.setSmallIcon(R.drawable.ic_launcher);
                mBuilder.setAutoCancel(true);
                mBuilder.setContentTitle("test");
                mBuilder.setContentText("test2");
                Intent resultIntent = new Intent (getBaseContext(), ControllerTestingScreen.class);
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(getBaseContext());
                stackBuilder.addParentStack(ControllerTestingScreen.class);
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
                mBuilder.setContentIntent(resultPendingIntent);
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                mBuilder.setDefaults(Notification.DEFAULT_ALL);
                mNotificationManager.notify(0, mBuilder.build());
            }
        };
        notibutton.setOnClickListener(nbuttonListener);
    }
}

服务类:

    package com.example.whereyouapp;

    import java.util.Arrays;

    import android.app.AlarmManager;
    import android.app.PendingIntent;
    import android.app.Service;
    import android.content.ContentValues;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.telephony.SmsManager;
    import android.widget.Toast;

    public class Controller extends Service 
    {

    double radius_distance=.8;
    private static final int POLL_INTERVAL = 1000 *3;
    static int number_of_times=0;

    Location currentLocation;
    static LocationManager locationManager;
    double distance;
    // Define a listener that responds to location updates

    LocationListener locationListenerGps = new LocationListener() 
    {
        public void onLocationChanged(Location location) 
        {
            currentLocation = location;
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };


    public static double coordinatesDistance(double lat1, double lon1, double lat2, double lon2)
    {
        //returns distance in kilometers between two coordinates
        double deltaLat = Math.toRadians(lat2-lat1);
        double deltaLong = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
        double a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.sin(deltaLong / 2) * Math.sin(deltaLong / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return 6371 * c; 
    }

    public int onStartCommand(Intent intent,int flags, int startId)
    {
        System.out.println("Working");
       Toast.makeText(this, "inside onStartCommans", Toast.LENGTH_LONG).show();
        //sendSMS("5613500110","If you received this text message then the Service class for WhereYouApp works");

        if ( locationManager != null )
        {

            // Register the listener with the Location Manager to receive location updates
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerGps);
            currentLocation  = locationManager.getLastKnownLocation( LocationManager.NETWORK_PROVIDER );

        }

        if( currentLocation != null )
        {

            Toast.makeText(this, currentLocation.getLatitude()+"       "+currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
            distance=coordinatesDistance(currentLocation.getLatitude(),currentLocation.getLongitude(),29.642,-82.344);
            Toast.makeText(this, ""+distance, Toast.LENGTH_SHORT).show();


        }
        else
        {
            System.out.println  ( "location not found" );
        }


        if(distance<=radius_distance){

        }

        if(number_of_times==0)
        {
            setServiceAlarm(getBaseContext(),false);
            number_of_times=-1;
        }
        number_of_times++;
        return START_NOT_STICKY;
    }

    public void onDestroy()
    {
        super.onDestroy();
        Toast.makeText(this, "yolo- the service has stopped working", Toast.LENGTH_LONG).show();
    }

    public void sendSMS(String phoneNumber, String message) 
    {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, null, null);
        ContentValues values = new ContentValues(); 
        values.put("address", phoneNumber); 
        values.put("body", message); 
        getContentResolver().insert(Uri.parse("content://sms/sent"), values);
    }

    public static void setServiceAlarm(Context context, boolean isOn)
    {

        System.out.println("inside the setServiceAlarm");
        // Acquire a reference to the system Location Manager
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Intent i = new Intent(context, Controller.class);
        PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        if (isOn) 
        {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), POLL_INTERVAL, pi);
        } 
        else 
        {
            alarmManager.cancel(pi);
            pi.cancel();
        }
    }

    @Override
    public IBinder onBind(Intent intent) 
    {
        return null;
    }

1 个答案:

答案 0 :(得分:1)

您应该在androidmanifest.xml中注册服务类,例如

 <service
        android:name="[your service class]"
        android:enabled="true"
        android:icon="@drawable/ic_launcher" >
    </service>