繁体   English   中英

当应用未在android中运行时,推送通知未显示

[英]Push Notification is not showing when app is not running in android

我在项目中使用了推送通知,它工作正常,但是当我的应用未运行时,它不工作。 仅在我的应用程序打开时显示。

这是我的GCMIntentService.java

public class GCMIntentService extends GCMBaseIntentService {

private static final String TAG = "GCMIntentService";

public GCMIntentService() {
    super(SENDER_ID);
}

/**
 * Method called on device registered
 **/
@Override
protected void onRegistered(Context context, String registrationId) {
    Toast.makeText(getApplicationContext(), "on res", 11).show();
    Log.i(TAG, "Device registered: regId = " + registrationId);
    displayMessage(context, "Your device "+registrationId);

    ServerUtilities.register(context, "", "", registrationId);
}

/**
 * Method called on device un registred
 * */
@Override
protected void onUnregistered(Context context, String registrationId) {
    Toast.makeText(getApplicationContext(), "on fail", 11).show();
    Log.i(TAG, "Device unregistered");
    displayMessage(context, getString(R.string.gcm_unregistered));
    ServerUtilities.unregister(context, registrationId);
}

/**
 * Method called on Receiving a new message
 * */
@Override
protected void onMessage(Context context, Intent intent) {
    Log.i(TAG, "Received message");
    String message = intent.getExtras().getString("price");

    displayMessage(context, message);

 //   

    // notifies user
    generateNotification(context, message);




}

/**
 * Method called on receiving a deleted message
 * */
@Override
protected void onDeletedMessages(Context context, int total) {
    Log.i(TAG, "Received deleted messages notification");
    String message = getString(R.string.gcm_deleted, total);
    PowerManager.WakeLock sWakeLock;
    //int pm = PowerManager.FromContext(context);
  //  sWakeLock = pm.NewWakeLock(WakeLockFlags.Partial, "GCM Broadcast Reciever Tag");
    //sWakeLock.Acquire();
    WakeLocker.acquire(getApplicationContext());
    displayMessage(context, message);

        /*if (extras.getString("message").length() != 0) {
        createNotification(context, extras);
        }*/
        generateNotification(context, message);//registration id on gcm device registratio

    // notifies user

        WakeLocker.release();


}

/**
 * Method called on Error
 * */
@Override
public void onError(Context context, String errorId) {
    Log.i(TAG, "Received error: " + errorId);
    displayMessage(context, getString(R.string.gcm_error, errorId));
}

@Override
protected boolean onRecoverableError(Context context, String errorId) {
    // log message
    Log.i(TAG, "Received recoverable error: " + errorId);
    displayMessage(context, getString(R.string.gcm_recoverable_error,
            errorId));
    return super.onRecoverableError(context, errorId);
}

/**
 * Issues a notification to inform the user that server has sent a message.
 */
private static void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context, Login.class);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
            Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent =
            PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    notification.defaults |= Notification.DEFAULT_SOUND;

    //notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");

    // Vibrate if vibrate is enabled
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);      
}

}

这是我的广播课:

    public class Login extends ActionBarActivity {


    Button login;
    JSONParserwithdata jsonParser = new JSONParserwithdata();
   public static String RegId ="";
   public static String deviceid ="";
    public database db;
    ConnectionDetector conDetector; 
    Boolean shutDown = false;
    Boolean netStatus=false;
    EditText school_id,mobile,password; 
    String user_id;
    AsyncTask<Void, Void, Void> mRegisterTask;

    // Alert dialog manager
    AlertDialogManager alert = new AlertDialogManager();

    // Connection detector
    ConnectionDetector cd;

     String school_id_db,mobileno_db,pssword_db,device_id_db;
    ProgressDialog pDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        final AlertDialog ad=new AlertDialog.Builder(this).create();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ///code for push notification device registered
        try{
        cd = new ConnectionDetector(getApplicationContext());

        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(Login.this,
                    "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }

        // Getting name, email from intent
        Intent i = getIntent();

        /*name = i.getStringExtra("name");
        email = i.getStringExtra("email");*/        

        // Make sure the device has the proper dependencies.

        GCMRegistrar.checkDevice(this);

        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(this);

        //lblMessage = (TextView) findViewById(R.id.lblMessage);

        registerReceiver(mHandleMessageReceiver, new IntentFilter(
                DISPLAY_MESSAGE_ACTION));

        // Get GCM registration id
        final String regId = GCMRegistrar.getRegistrationId(this);

        // (Check if regid already presents
        if (regId.equals("")) {
            // Registration is not present, register now with GCM           
            GCMRegistrar.register(this, SENDER_ID);

        } else {
            // Device is already registered on GCM
            if (GCMRegistrar.isRegisteredOnServer(this)) {
                // Skips registration.              
                Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
            } else {
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                Toast.makeText(getApplicationContext(), "id "+regId, Toast.LENGTH_LONG).show();

                /*final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        // Register on our server
                        // On server creates a new user
                        ServerUtilities.register(context, name, email, regId);
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }

                };
                mRegisterTask.execute(null, null, null);*/
            }
        }
        }
        catch(Exception e)
        {
            ad.setMessage(e.getMessage());
            ad.show();
        }
        //end for device registration
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#66BF77")));
        conDetector= new ConnectionDetector(this);
        school_id=(EditText)findViewById(R.id.school_id);
        password=(EditText)findViewById(R.id.password);
        mobile=(EditText)findViewById(R.id.mobile_no);
        login=(Button)findViewById(R.id.sign_in);
         db=new database(this);

        TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);

        device_id_db = tm.getDeviceId();

        login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //final AlertDialog ad=new AlertDialog.Builder(this).create();
                String VRegId=RegId;
                RegId=RegId.replace("Your device ", "");
                int pos2=RegId.indexOf("Trying");
                if(pos2>0)
                RegId=RegId.substring(0,pos2);

                if(mobile.getText().toString().length()!=0)
                {
                    if(school_id.getText().toString().length()!=0)
                    {
                        if(password.getText().toString().length()!=0)
                        {

                             netStatus=conDetector.isConnectingToInternet();
                                if(netStatus)
                                    { 
                                     AttemptLogin task = new AttemptLogin();
                                       task.execute();
                                    }
                                else
                                {
                                    Toast.makeText(getBaseContext(), "Internet connection problem", Toast.LENGTH_LONG).show();

                                }

                        }
                        else
                        {
                            password.setError("Please enter password");
                        }
                    }
                    else
                    {
                        school_id.setError("Please enter school id");   
                    }
                }
                else
                {
                    mobile.setError("Please enter mobile number");
                }
            }
        });
    }
    class AttemptLogin extends AsyncTask<String, String, String> {

         String success_response;
         int postpg=0;
         String type;
         String sc_id;
         String logo_url;
         String actionbar_title,target_data;
         JSONArray targetrarry,userArray;
         /**
         * Before starting background thread Show Progress Dialog
         * */
        boolean failure = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setCanceledOnTouchOutside(false);

            pDialog.setMessage("Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub


            try {



                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("mobileno",mobile.getText().toString()));
                params.add(new BasicNameValuePair("uid", school_id.getText().toString()));
                params.add(new BasicNameValuePair("pass", password.getText().toString()));
                params.add(new BasicNameValuePair("regid", RegId));
                params.add(new BasicNameValuePair("deviceid", deviceid));
                JSONArray mainjson = jsonParser.makeHttpRequest(
                        "http://ddlindialtd.com/webservice/service1.asmx/getSchool", "POST", params);
                for(int i=0; i<mainjson.length(); i++)
                {
                     JSONObject mainobj=mainjson.getJSONObject(i);
                      success_response=mainobj.getString("status");
                      JSONArray resultjsonarray = mainobj.getJSONArray("result");


                      for(int j=0; j<resultjsonarray.length(); j++)
                        {
                          JSONObject innerobj=resultjsonarray.getJSONObject(j);
                            type=innerobj.getString("Usertype");
                            logo_url=innerobj.getString("schoolLogo");
                            actionbar_title=innerobj.getString("schoolTitle");
                            sc_id=innerobj.getString("id");
                            targetrarry=innerobj.getJSONArray("targetdata");
                             userArray=innerobj.getJSONArray("userdata");
                             for(int k=0;k<userArray.length();k++)
                             {
                                  JSONObject userjsonobj=userArray.getJSONObject(k);
                                   user_id=userjsonobj.getString("vfromid");
                             }
                        }
                }


            } catch (Exception e) {

                success_response = getBaseContext().getString(R.string.error)+","+e.getMessage();
            }

            return success_response;

        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();

           if(file_url.equals("404 server error"))
            {
                 Toast.makeText(getBaseContext(), file_url, Toast.LENGTH_LONG).show();

            }
            else
            {
            if(file_url.equals("success"))
            {
                if(type.equals("parent"))
                {
                    mobileno_db=mobile.getText().toString();
                    school_id_db=school_id.getText().toString();
                    pssword_db=password.getText().toString();
                    db.store(user_id,type,mobileno_db,school_id_db,pssword_db,device_id_db,RegId,deviceid);

                    Intent intent=new Intent(Login.this,ListofClass.class);
                    intent.putExtra("Logo", logo_url);
                    intent.putExtra("Title", actionbar_title);
                    intent.putExtra("JSON", targetrarry.toString());
                    overridePendingTransition(R.animator.acitivity_transation, R.animator.activity_animation_2);
                    startActivity(intent);

                }
                else
                {
                    mobileno_db=mobile.getText().toString();
                    school_id_db=school_id.getText().toString();
                    pssword_db=password.getText().toString();
                    db.store(user_id,type,mobileno_db,school_id_db,pssword_db,device_id_db,RegId,deviceid);

                    Intent intent=new Intent(Login.this,ListofClass.class);
                    intent.putExtra("Logo", logo_url);
                    intent.putExtra("Title", actionbar_title);
                    intent.putExtra("JSON", targetrarry.toString());
                    overridePendingTransition(R.animator.acitivity_transation, R.animator.activity_animation_2);
                    startActivity(intent);

                }
            }
            else
            {
                Toast.makeText(getBaseContext(), "Unaouthorised Access", Toast.LENGTH_LONG).show();
            }
            }

        }

        }


    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //ComponentName comp=new ComponentName(context.getPackageName(),GCMIntentService.class.getName());
            //startWakefulService(context, intent.setComponent(comp));
            //WakeLocker.acquire(getApplicationContext());
            //setResultCode(Activity.RESULT_OK);
            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
            // Waking up mobile if it is sleeping
            WakeLocker.acquire(getApplicationContext());

            /**
             * Take appropriate action on this message
             * depending upon your app requirement
             * For now i am just displaying it on the screen
             * */

            // Showing received message
        //  lblMessage.append(newMessage + "\n");           
            Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
            //if(RegId.equals(""))
            RegId=RegId+newMessage;
            // Releasing wake lock
            WakeLocker.release();
        }
    };

    @Override
    protected void onDestroy() {
        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        try {
            unregisterReceiver(mHandleMessageReceiver);
            GCMRegistrar.onDestroy(this);
        } catch (Exception e) {
            Log.e("UnRegister Receiver Error", "> " + e.getMessage());
        }
        super.onDestroy();
    }

}

尝试在Android Manifest文件中授予WAKE_LOCK权限

<uses-permission android:name="android.permission.WAKE_LOCK" />

如果手机进入睡眠状态,它将使CPU唤醒

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM