即使服务正在运行,通知也不会显示

时间:2015-02-04 17:36:04

标签: java android multithreading service notifications

我正在构建一个应用程序,它在连接特定的wifi网络时可以正常工作。要检查我的wifi网络是否已连接,我正在运行一个后台服务,它在其中运行一个无限循环的线程。线程检查wifi连接是否有效。如果是,则显示通知并保持通知,直到wifi断开连接。我无法找到更好的方法来异步检查我的连接。我面临的问题如下: 如果服务已经运行并且我连接到网络,我会收到通知。现在我打开我的应用程序,通知仍然显示。然后我从wifi连接断开连接并且通知消失,我再次连接并且再次出现通知,因为它应该。现在,如果我从概览中删除我的应用程序,然后断开与wifi的连接,我的通知不会进入,它会粘在通知面板中。虽然这个错误是不确定的,并且在某些手机中出现而在某些手机中没有

我发布了我的服务代码和主要活动代码。 请建议我更好的方法来完成这项任务。

MyService.java



package com.sumatone.volsbbonetouch;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import java.util.logging.Handler;
import java.util.logging.LogRecord;

/**
 * Created by shalini on 31-01-2015.
 */
public class MyService extends Service {
    private boolean CHECK=true,tcheck=true;
    private Thread t1;
    @Override
    public void onCreate() {
        super.onCreate();
        final ShowNotification s=new ShowNotification(this);
        //Toast.makeText(this,"Service was created",Toast.LENGTH_SHORT).show();
        t1=new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    CHECK=checkConnection();
                    if (CHECK==true&&tcheck==true) {
                        Log.d("status", "connected");
                        s.notifyInstant();
                        tcheck=false;
                    }
                    else if (CHECK==false&&tcheck==false) {
                        Log.d("status", "disconnected");
                        s.remove();
                        tcheck=true;
                    }
                }
            }
        });
        /*t2=new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    checkConnection();
                    if (!CHECK) {
                        Log.d("status", "disconnected");
                        t1.notify();
                        try {
                            t2.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });*/

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //Toast.makeText(this,"Service was started",Toast.LENGTH_SHORT).show();
        t1.start();
        return super.onStartCommand(intent,flags,startId);
    }
    public boolean checkConnection() {
        /*final ConnectivityManager connMgr = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if(wifi.isConnected())
        {
            Log.d("wifi",wifi.getExtraInfo());
            if(wifi.getExtraInfo().equalsIgnoreCase("\"VOLSBB\"")) {
                Log.d("wifistate","connected");
                return true;
            }
            return false;
        }
        else {
            return false;
        }*/
        final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        final ConnectivityManager connMgr = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if(wifiManager.isWifiEnabled())
        {
            final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            final SupplicantState supp= wifiInfo.getSupplicantState();
            Log.d("wifi",wifiInfo.getSSID());
            if((wifiInfo.getSSID().equalsIgnoreCase("\"VOLSBB\"")||wifiInfo.getSSID().equalsIgnoreCase("\"VOLS\""))&&wifi.isConnected()) {
                Log.d("wifistate","connected");
                return true;
            }
            return false;
        }
        else {
            return false;
        }
    }

    @Override
    public void onDestroy() {

        //Toast.makeText(this,"Service was destroyed",Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }


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




MainActivity.java



package com.sumatone.volsbbonetouch;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

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

/**
 * Created by shalini on 29-01-2015.
 */
public class MainActivity extends Activity implements View.OnClickListener {
    private String url="http://phc.prontonetworks.com/cgi-bin/authlogin?URI=http://www.msftncsi.com/redirect";
    EditText uname,password;
    TextView res;
    Button login,logout,slogin;
    List<NameValuePair> details;
    ProgressDialog pDialog;
    SharedPreferences s;
    Authentication a;
    String u,p,toasttext,session;
    ImageView about;
    String service="ProntoAuthentication";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(!isMyServiceRunning(MyService.class))
        startService(new Intent(this,MyService.class));
        about=(ImageView)findViewById(R.id.about);
        uname=(EditText)findViewById(R.id.user);
        password=(EditText)findViewById(R.id.pass);
        s= PreferenceManager.getDefaultSharedPreferences(this);
        uname.setText(s.getString("prontousername",null));
        password.setText(s.getString("prontopassword",null));
        a= new Authentication(this);
        login=(Button)findViewById(R.id.login);
        logout=(Button)findViewById(R.id.logout);
        slogin=(Button)findViewById(R.id.savelogin);
        res=(TextView)findViewById(R.id.res);
        login.setOnClickListener(this);
        logout.setOnClickListener(this);
        slogin.setOnClickListener(this);
        about.setOnClickListener(this);
        session=s.getString("session","first");
        if(session.equals("first")){
            about.performClick();
            SharedPreferences.Editor editor=s.edit();
            editor.putString("session","used");
            editor.commit();
        }

    }

    @Override
    public void onClick(View v) {

            if (v.getId() == R.id.login) {
                if(checkConnection()) {
                    details = new ArrayList<NameValuePair>();
                    url = "http://phc.prontonetworks.com/cgi-bin/authlogin?URI=http://www.msftncsi.com/redirect";
                    u = uname.getText().toString();
                    p = password.getText().toString();
                    details.add(new BasicNameValuePair("userId", u));
                    details.add(new BasicNameValuePair("password", p));
                    details.add(new BasicNameValuePair("serviceName", service));
                    new GetEvents().execute();
                }
                else
                    Toast.makeText(this,"Not connected to Volsbb",Toast.LENGTH_SHORT).show();
            }
            if (v.getId() == R.id.logout) {
                if(checkConnection()) {
                    details = null;
                    url = "http://phc.prontonetworks.com/cgi-bin/authlogout";
                    new GetEvents().execute();
                }
                else
                    Toast.makeText(this,"Not connected to Volsbb",Toast.LENGTH_SHORT).show();

            }
            if (v.getId() == R.id.savelogin) {
                if (checkConnection()) {
                    details = new ArrayList<NameValuePair>();
                    url = "http://phc.prontonetworks.com/cgi-bin/authlogin?URI=http://www.msftncsi.com/redirect";
                    u = uname.getText().toString();
                    p = password.getText().toString();
                    SharedPreferences.Editor editor = s.edit();
                    editor.putString("prontousername", u);
                    editor.putString("prontopassword", p);
                    editor.commit();
                    details.add(new BasicNameValuePair("userId", u));
                    details.add(new BasicNameValuePair("password", p));
                    details.add(new BasicNameValuePair("serviceName", service));
                    new GetEvents().execute();
                } else
                    Toast.makeText(this, "Not connected to Volsbb", Toast.LENGTH_SHORT).show();
            }


            if(v.getId()==R.id.about)
            {
                Intent i= new Intent(this,AboutDialog.class);
                startActivity(i);
            }

    }
    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    public boolean checkConnection() {
        /*final ConnectivityManager connMgr = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if(wifi.isConnected())
        {
            Log.d("wifi",wifi.getExtraInfo());
            if(wifi.getExtraInfo().equalsIgnoreCase("\"VOLSBB\"")) {
                Log.d("wifistate","connected");
                return true;
            }
            return false;
        }
        else {
            return false;
        }*/
        final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        if(wifiManager.isWifiEnabled())
        {
            final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            Log.d("wifi",wifiInfo.getSSID());
            if(wifiInfo.getSSID().equalsIgnoreCase("\"VOLSBB\"")) {
                Log.d("wifistate","connected");
                return true;
            }
            return false;
        }
        else {
            return false;
        }
    }

    private class GetEvents extends AsyncTask<Void, Void,String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Processing");
            pDialog.setCancelable(false);
            pDialog.show();

        }
        @Override
        protected String doInBackground(Void... params) {
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String valresponse = sh.makeServiceCall(url, ServiceHandler.POST,details);
            Log.d("Response: ", ">" + valresponse);
            return valresponse;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            if(result.contains("Logout successful"))
                toasttext="Logged out";
            else if(result.contains("Successful Pronto Authentication"))
                toasttext="Logged in";
            else if(result.contains("There is no active session to logout"))
                toasttext="There is no active session";
            else if(result.contains("Sorry, please check your username and password"))
                toasttext="Invalid username/password";
            else if(result.contains("Sorry, your free access quota is over"))
                toasttext="Your free access qouta is over";
            else
                toasttext="Already Logged in";
            Toast.makeText(getApplicationContext(),toasttext,Toast.LENGTH_SHORT).show();
        }



}
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您必须在onStartCommand()中返回START_STICKY以保持服务正常运行。 START_STICKY告诉操作系统重新创建服务,如果它因某种原因被杀死(即内存,手动查杀应用程序)。

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
      super.onStartCommand(intent, flags, startId);
      //Your service code

      return START_STICKY;
 }