连接检测器通过后台服务返回false

时间:2018-03-19 06:57:56

标签: android android-service android-connectivitymanager

在我的应用程序中,我希望通过前端服务和接收器获得GPS位置。一切都运行良好,但经过两三次成功运行。服务无法检测互联网并返回错误

这是代码

活动中呼叫服务接收者的代码

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent ll24 = new Intent(getBaseContext(), AlarmReceiver.class);
    PendingIntent recurringLl24 = PendingIntent.getBroadcast(getBaseContext(), 0, ll24, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarms.setRepeating(AlarmManager.RTC_WAKEUP,0, 30*10*100, recurringLl24);
   }
 //.....
}

&安培;在接收器类

public class AlarmReceiver extends WakefulBroadcastReceiver 
{   
    static Context context;
    Date curTime,sdf,edf;
    private static final String LOG_TAG = "ForegroundService";

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        try 
        {
            Calendar c =  Calendar.getInstance();
            curTime =  new SimpleDateFormat( "HH:mm" ).parse(c.get( Calendar.HOUR_OF_DAY)+":"+c.get( Calendar.MINUTE));
            sdf = new SimpleDateFormat( "HH:mm" ).parse("08:00");
            edf = new SimpleDateFormat( "HH:mm" ).parse("20:00");    
            if(curTime.after(sdf) && curTime.before(edf))
            {
                Intent ll24Service = new Intent(context, ForegroundService.class);
                ll24Service.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
                ForegroundService.IS_SERVICE_RUNNING = true;
                startWakefulService(context,ll24Service);   
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 }

在服务类

public class ForegroundService extends Service 
{
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{
    AlarmReceiver.completeWakefulIntent(intent);
    if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) 
    {
        Log.i(LOG_TAG, "Received Start Foreground Intent ");
        showNotification();

        Calendar c =  Calendar.getInstance();
        curDateTime  = c.get( Calendar.YEAR)+"-"+ String.valueOf(c.get( Calendar.MONTH )+1)+"-"+ c.get( Calendar.DAY_OF_MONTH)+" "+c.get( Calendar.HOUR_OF_DAY)+":"+c.get( Calendar.MINUTE)+":"+c.get( Calendar.SECOND);

        gps = new GPS(ForegroundService.this);
        if(gps.canGetLocation())
        {
            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();
            latt=Double.toString(latitude);
            longi =String.valueOf(longitude);

            insertData();   
        }
        else
        {
            gps.showSettingsAlert();
        }   
    } 

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i(LOG_TAG, "In onDestroy");
}

private void insertData() 
{
    try
    {
        String QUERY = "insert into GpsLoc values('"+usr+"','"+latt+"','"+longi+"','"+curDateTime+"')";
        myDatabase.execSQL(QUERY);

        Log.i(LOG_TAG, "insert");
        ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
        Boolean isInternetPresent = cd.isConnectingToInternet();

        if(isInternetPresent)
        {
            Log.i(LOG_TAG, "chk int");
            addToJason();
        }
        else
        {
            Log.i(LOG_TAG, "No int");
            stopForeground(true);
            stopSelf();
        }



    }
    catch(Exception ex)
    {
        Toast.makeText(getApplicationContext(), "Data not inserted : "+ex.toString(), Toast.LENGTH_LONG).show();
    }
}

如日志所示,每件事情都运行正常:

  

03-19 12:11:48.160:I / ForegroundService(17476):收到开始   前景意图

     

03-19 12:11:48.270:D /网络(17476):网络

     

03-19 12:11:48.340:I / ForegroundService(17476):insert

     

03-19 12:11:48.390:I / ForegroundService(17476):chk int

     

03-19 12:11:49.340:I / ForegroundService(17476):已上传

     

03-19 12:11:49.350:I / ForegroundService(17476):在onDestroy

但是经过两三次运行相同的日志后

  

03-19 12:15:34.670:I / ForegroundService(17476):收到开始前景意图

     

03-19 12:15:34.740:D /网络(17476):网络

     

03-19 12:15:34.780:I / ForegroundService(17476):insert

     

03-19 12:15:34.780:I / ForegroundService(17476):No int

     

03-19 12:15:34.850:I / ForegroundService(17476):在onDestroy

问题在于在应用未运行时检查互联网连接,并且通过服务调用它。请建议任何解决方案

有时它会惹恼:

  

03-27 12:30:07.240:I / ForegroundService(1543):   android.view.WindowManager $ BadTokenException:无法添加窗口 -   token null不适用于应用程序

有时:转换结果jsonobject时出错

请帮助问题Strat这里当我们打电话来检测服务中的互联网时

ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
Boolean isInternetPresent = cd.isConnectingToInternet();

1 个答案:

答案 0 :(得分:1)

gradle文件中添加此依赖项。

compile 'com.firebase:firebase-jobdispatcher:0.8.5'

创建Firebase JobService个文件并在manifest中声明。

<service
        android:exported="false"
        android:name="._User_Classes.User_Call_Record.ScheduledJobService">
        <intent-filter>
        <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
        </intent-filter>
        </service>

JobService或片段

声明并启动activity
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
        Job myJob = dispatcher.newJobBuilder()
                .setService(ScheduledJobService.class) // the JobService that will be called
                .setRecurring(false) //repeat the job or not

                .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
                .setTrigger(Trigger.executionWindow(0, 60))
                .setLifetime(Lifetime.FOREVER)
                .setTag("demo")        // uniquely identifies the job
                .build();
        dispatcher.mustSchedule(myJob);

以下是每次执行作业时将调用的JobService类。

public class ScheduledJobService extends JobService {

    @Override
    public boolean onStartJob(JobParameters job) {
    if(isConnected(this))
{
//internet available
}
else{
//internet not available
}
       //perform your operations
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new 
        GooglePlayDriver(this));
        Job myJob = dispatcher.newJobBuilder()
                .setService(ScheduledJobService.class) // the JobService that will be called
                .setRecurring(false) //repeat the job or not
                .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
                .setTrigger(Trigger.executionWindow(0, 60))
                .setLifetime(Lifetime.FOREVER)
                .setTag("demo")        // uniquely identifies the job
                .build();
        dispatcher.mustSchedule(myJob);
        return true;
    }






    @Override
    public boolean onStopJob(JobParameters job) {
        return false;
    }

 public static NetworkInfo getNetworkInfo(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo();
    }

    /**
     * Check if there is any connectivity
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        NetworkInfo info = getNetworkInfo(context);
        return (info != null && info.isConnected());
    }

}

我希望它有所帮助