如何在不打开应用程序的情况下定期运行服务

时间:2017-03-06 09:08:50

标签: android

嗨我正在开发一个应用程序,我需要从手机上获取未读短信。我需要在固定的时间内检查我的收件箱。我已经编写了代码来检索未读短信。我已经包含了一个计时器,每30秒检查一次未读短信。但问题是它只在应用程序打开时进行检查。即使应用程序未打开,我也需要检查。请提供我需要提出的任何建议和修改。以下是我的代码。

MainActivity

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends ActionBarActivity {

MyReceiver myReceiver;
ListView lViewSMS;
ArrayList datapassed;
//private static final String TAG_SUCCESS = "success";

//String URL = "http://10.10.234.232/test_android/index2.php";

// JSONParser jsonParser = new JSONParser();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lViewSMS = (ListView) findViewById(R.id.listViewSMS);

    //String []r;
    // r=new String[2];

    // if (r != null) {
    //@SuppressWarnings("unchecked")
    //ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, fetchInbox());
    //lViewSMS.setAdapter(adapter);/
    //AttemptLogin attemptLogin = new AttemptLogin();
    //attemptLogin.execute(r[0],r[1]);
  //  @SuppressWarnings("unchecked")
   // ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datapassed);
    //lViewSMS.setAdapter(adapter);

}

@Override
protected void onStart() {
    // TODO Auto-generated method stub

    //Register BroadcastReceiver
    //to receive event from our service
    myReceiver = new MyReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(MyService.MY_ACTION);
    registerReceiver(myReceiver, intentFilter);

    //Start our own service
    Timer t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            Intent intent = new Intent(MainActivity.this, MyService.class);
            startService(intent);
        }
    },
            0,
            30000);
    super.onStart();
}

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    unregisterReceiver(myReceiver);
    super.onStop();
}

private class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub

        datapassed = arg1.getStringArrayListExtra("DATAPASSED");
       // @SuppressWarnings("unchecked")
       // ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datapassed);
       // lViewSMS.setAdapter(adapter);
        Toast.makeText(MainActivity.this,
                "Triggered by Service!\n"
                        + "Data passed: " + datapassed,
                Toast.LENGTH_LONG).show();

    }


}
}

MyService.java

import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;

import java.util.ArrayList;


public class MyService extends Service {
final static String MY_ACTION = "MY_ACTION";

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub

    MyThread myThread = new MyThread();
    myThread.start();

    return super.onStartCommand(intent, flags, startId);
}
public class MyThread extends Thread{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            //Thread.sleep(5000);

            Intent intent = new Intent();
            intent.setAction(MY_ACTION);
            if(fetchInbox()!=null) {
                intent.putExtra("DATAPASSED", fetchInbox());

                sendBroadcast(intent);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        stopSelf();
    }

}
ArrayList fetchInbox (){

    final Uri SMS_INBOX = Uri.parse("content://sms/inbox");

    //Retrieves all SMS (if you want only unread SMS, put "read = 0" for the 3rd parameter)
    Cursor cursor = getContentResolver().query(SMS_INBOX, null,"read=0", null, null);
    ArrayList sms = new ArrayList();
    //Get all lines
    String read=" ";
    String body=" ";
    String[] arr = new String[2];
    while (cursor.moveToNext()) {
        //Gets the SMS information
        String address = cursor.getString(cursor.getColumnIndex("address"));
        String person = cursor.getString(cursor.getColumnIndex("person"));
        String date = cursor.getString(cursor.getColumnIndex("date"));
        String protocol = cursor.getString(cursor.getColumnIndex("protocol"));
        read = cursor.getString(cursor.getColumnIndex("read"));
        String status = cursor.getString(cursor.getColumnIndex("status"));
        String type = cursor.getString(cursor.getColumnIndex("type"));
        String subject = cursor.getString(cursor.getColumnIndex("subject"));
        body = cursor.getString(cursor.getColumnIndex("body"));

        sms.add(address+"\n"+person+"\n"+body+"\n");
        //Do what you want

        //   else
        // {
        //   AttemptLogin attemptLogin = new AttemptLogin();
        // attemptLogin.execute("", "");
        //}
    }
    //return arr;
    //return body;
    return sms;
}
}

4 个答案:

答案 0 :(得分:1)

您可以使用Android中的AlarmManager Class定期运行服务。

 AlarmManager alarmMgr= (AlarmManager)
 context.getSystemService(Context.ALARM_SERVICE);

            int timeInterval=300*1000;//in milliseconds
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());

            Intent intent = new Intent(context, YourService.class);
            alarmIntent = PendingIntent.getService(context, 0, intent, 0);
            alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), timeInterval, alarmIntent);`

答案 1 :(得分:0)

您需要在Service而不是Activity

中重复执行此操作

所以你开始服务一次:

@Override
protected void onStart() {
    // TODO Auto-generated method stub

    //Register BroadcastReceiver
    //to receive event from our service
    myReceiver = new MyReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(MyService.MY_ACTION);
    registerReceiver(myReceiver, intentFilter);

    //Start our own service
        Intent intent = new Intent(MainActivity.this, MyService.class);
        startService(intent);
    super.onStart();

}

并在您的服务中

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Timer t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            MyThread myThread = new MyThread();
            myThread.start();
        }
    }, 0, 30000);
    return super.onStartCommand(intent, flags, startId);
}

同时从stopSelf();

中删除MyThread

一次尝试传递广播中收到的context,而不是Activity

答案 2 :(得分:0)

您可以在示例

中使用AlarmManeger类https://developer.android.com/training/scheduling/alarms.html
 Calendar calendar = Calendar.getInstance();
    long repeatInterval = 30000;
    AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(getActivity(), MyReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(getActivity(), 0, i, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), repeatInterval , pi);

其中repeatInterval时间,以毫秒为单位。 当MyReceiver收到Intent广播时,会调用onReceive()。

答案 3 :(得分:0)

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends ActionBarActivity {

    MyReceiver myReceiver;
    ListView lViewSMS;
    ArrayList datapassed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lViewSMS = (ListView) findViewById(R.id.listViewSMS);

        Calendar calendar = Calendar.getInstance();
        long repeatInterval = 30000;
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(this, MyServiceReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), repeatInterval, pi);

    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub

        //Register BroadcastReceiver
        //to receive event from our service
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MyService.MY_ACTION);
        registerReceiver(myReceiver, intentFilter);

        //Start our own service
        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
                                  @Override
                                  public void run() {

                                      Intent intent = new Intent(MainActivity.this, MyService.class);
                                      startService(intent);
                                  }
                              },
                0,
                30000);
        super.onStart();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        unregisterReceiver(myReceiver);
        super.onStop();
    }

    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            // TODO Auto-generated method stub

            datapassed = arg1.getStringArrayListExtra("DATAPASSED");
            // @SuppressWarnings("unchecked")
            // ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datapassed);
            // lViewSMS.setAdapter(adapter);
            Toast.makeText(MainActivity.this,
                    "Triggered by Service!\n"
                            + "Data passed: " + datapassed,
                    Toast.LENGTH_LONG).show();

        }


    }
}




import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

public class MyServiceReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ComponentName comp = new ComponentName(context.getPackageName(), MyService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
    }
}


Try above code