无法从活动中调用服务

时间:2016-04-16 07:18:43

标签: android

您好我认为我做得对,但不知道我在哪里滞后。这是我的代码,我从主要活动开始服务但服务没有开始。如果有人知道请帮帮我。 MainActivity

package com.example.lalit.gcmtest;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.widget.ImageView;
import android.widget.Toast;


import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity  {
    JsonParser jsonParser = new JsonParser();
    String str;
    private static final String TAG_SUCCESS = "success";
    public static final String NOTIFICATION_URL = "http://kushjalwa.netau.net/tokenStore.php";
    public static final String TOKEN_URL = "http://kushjalwa.netau.net/Token_Registration.php";
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private static final String TAG = "MainActivity";

    private BroadcastReceiver mRegistrationBroadcastReceiver;
    //public ProgressDialog progress;

    ProgressDialog pDialog;

    static boolean flag=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        if (flag) {

            Intent intent = new Intent(this, MyRegistrationIntentService.class);
            startService(intent);
            flag=false;
        }
        else {
            Intent i=getIntent();
            str=i.getStringExtra("token");
            Log.d("Token in Activity",str);
            Log.d("CheckPoint", "check");
            new SendingNotification().execute();
        }
    }


    public class SendingNotification extends AsyncTask<String, String, String> {



        int success;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("......Registering.......");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        @Override
        protected String doInBackground(String... args)
        {
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("token", str));
                Log.d("request!", "heloo");
                JSONObject json = jsonParser.makeHttpRequest(TOKEN_URL, "POST", params);
                Log.d("Login attempt", json.toString());
                success = json.getInt(TAG_SUCCESS);
                if (success == 1)
                {
                    Log.d("Login Successful!", json.toString());
                }
                else
                {
                    Log.d("Sendind Fail", "Fail");
                }
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
            return null;
        }
        protected void onPostExecute(String file_url)
        {

            pDialog.dismiss();
            Toast.makeText(getApplicationContext(), "Token Stored", Toast.LENGTH_SHORT).show();
        }


    }
}



Service

package com.example.lalit.gcmtest;

import android.app.IntentService;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;


public class MyRegistrationIntentService extends IntentService {

    public static String token = null;
    private static final String TAG_SUCCESS = "success";
    private static final String TAG = "RegIntentService";
    public static final String TOKEN_URL = "http://kushjalwa.netau.net/Token_Registration.php";
    public static final String NOTIFICATION_URL = "http://kushjalwa.netau.net/ceo.php";
    private static final String[] TOPICS = {"global"};
    public ProgressDialog pDialog;
    Context context;
    JsonParser jsonParser = new JsonParser();

    public MyRegistrationIntentService() {
        super(TAG);
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        try {

            synchronized (TAG) {

                InstanceID instanceID = InstanceID.getInstance(this);
                token = instanceID.getToken("879100952974",
                        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                // [END get_token]
                Log.i(TAG, "GCM Registration Token: " + token);

                Intent dialogIntent = new Intent(this, MainActivity.class);
                dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                dialogIntent.putExtra("token",token);
                startActivity(dialogIntent);


                sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
                // [END register_for_gcm]
            }
        } catch (Exception e) {
            Log.d(TAG, "Failed to complete token refresh", e);
            sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
        }
        Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
    }


    public class SendingToken extends AsyncTask<String, String, String> {

        int success;

        /* private ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
         InputStream inputStream = null;
         String result = "";
 */
        protected void onPreExecute() {
           /* progressDialog.setMessage("Your progress dialog message...");
            progressDialog.show();
            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface arg0) {
                    //MyAsyncTask.this.cancel(true);
                }
            });*/
        }



        @Override
        protected String doInBackground(String... args) {
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("token", token));


                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(TOKEN_URL, "POST", params);


                Log.d("Login attempt", json.toString());

                // json success tag
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("Login Successful!", json.toString());
                } else {
                    Log.d("Sendind Fail", "Fail");
                }
            } catch (Exception ex) {
            }
            // [END subscribe_topics]
            return null;
//}
        }

        @Override
        protected void onPostExecute(String s) {

            //   pDialog.dismiss();
        }
    }


}

1 个答案:

答案 0 :(得分:0)

通过声明清单中的服务一切正常。