如何在后台发送消息而无需每次都运行应用程序

时间:2016-04-06 05:30:11

标签: android sms

我想在温度高于阈值时向用户发送消息。 这是发送消息的屏幕。应用程序应该在后台运行并继续检查温度是否超过阈值并且den应该发送消息。

package com.gopal.coldstorage;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.gopal.coldstorage.R;

import java.util.Calendar;

public class Dashboard extends Activity {

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    String sn, de, da, ti, te;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dashboard);
        TextView tv1 = (TextView) findViewById(R.id.textView22);
        TextView hi = (TextView) findViewById(R.id.textView13);
        TextView lo = (TextView) findViewById(R.id.textView14);
        TextView hi1 = (TextView) findViewById(R.id.textView15);
        TextView lo1 = (TextView) findViewById(R.id.textView19);
        TextView hig = (TextView) findViewById(R.id.textView16);
        TextView lowe = (TextView) findViewById(R.id.textView17);
        TextView higherm = (TextView) findViewById(R.id.textView18);
        TextView lowerm = (TextView) findViewById(R.id.textView20);
        int count = 0, count1 = 0, count1m = 0, countm = 0, tm = 0;
        SQLiteDatabase db = openOrCreateDatabase("SData", MODE_PRIVATE, null);
        Cursor cur = db.rawQuery("select distinct temp from sdata where date='2016-03-03'", null);
        cur.moveToLast();
        int c1 = cur.getColumnIndex("temp");
        String temp = cur.getString(c1);
        final int t = Integer.parseInt(temp);
        tv1.setText(temp);
        Calendar c = Calendar.getInstance();
        Cursor cur1 = db.rawQuery("select max(temp) as max,min(temp) as min from sdata where date='2016-03-03'", null);
        cur1.moveToFirst();
        int id = cur1.getColumnIndex("max");
        int id1 = cur1.getColumnIndex("min");
        String max = cur1.getString(id);
        String min = cur1.getString(id1);
        hi.setText(max);
        lo.setText(min);
        SQLiteDatabase dbn = openOrCreateDatabase("thres", MODE_PRIVATE, null);
        Cursor curser1 = db.rawQuery("select  temp from sdata where date='2016-03-03'", null);
        curser1.moveToFirst();
        int high = 0;
        int low = 0;
        if (curser1 != null) {
            do {
                int c11 = curser1.getColumnIndex("temp");
                String tempd = curser1.getString(c11);
                int td = Integer.parseInt(tempd);
                Cursor curs = dbn.rawQuery("select high,low from threshold", null);
                curs.moveToLast();
                int c2 = curs.getColumnIndex("high");
                int c3 = curs.getColumnIndex("low");
                String h1 = curs.getString(c2);
                String l1 = curs.getString(c3);

                high = Integer.parseInt(h1);
                if (td > high) {
                    count++;
                }
                low = Integer.parseInt(l1);
                if (td < low) {
                    count1++;
                }
            } while (curser1.moveToNext());
        }

        hig.setText(String.valueOf(count));
        lowe.setText(String.valueOf(count1));
        Cursor curn = db.rawQuery("select temp from sdata where date like '2016-03%'", null);
        curn.moveToFirst();
        if (curn != null) {
            do {
                int cn = curn.getColumnIndex("temp");
                String tempm = curn.getString(cn);
                tm = Integer.parseInt(tempm);
                Cursor curser = dbn.rawQuery("select high,low from threshold", null);
                curser.moveToLast();
                int c2 = curser.getColumnIndex("high");
                int c3 = curser.getColumnIndex("low");
                String h1 = curser.getString(c2);
                String l1 = curser.getString(c3);

                int highm = Integer.parseInt(h1);
                if (tm > highm) {
                    countm++;
                }
                int lowm = Integer.parseInt(l1);
                if (tm < lowm) {
                    count1m++;
                }
            } while (curn.moveToNext());
        }

        higherm.setText(String.valueOf(countm));
        lowerm.setText(String.valueOf(count1m));
        Cursor cur2 = db.rawQuery("select max(temp) as max,min(temp) as min from sdata where date like '2016-03%'", null);
        cur2.moveToFirst();
        int id2 = cur2.getColumnIndex("max");
        int id3 = cur2.getColumnIndex("min");
        String max1 = cur2.getString(id2);
        String min1 = cur2.getString(id3);
        hi1.setText(max1);
        lo1.setText(min1);
        final TextView tv = (TextView) findViewById(R.id.textView23);
        Bundle b = getIntent().getExtras();
        String s = b.getString("value");
        tv.setText(s);
        TextView time = (TextView) findViewById(R.id.textView21);

        String sTime = c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND);
        time.setText(sTime);
        TextView date = (TextView) findViewById(R.id.textView3);
        String mon = null;
        int month = c.get(Calendar.MONTH) + 1;
        switch (month) {
            case 1:
                mon = "JAN";
                break;
            case 2:
                mon = "FEB";
                break;
            case 3:
                mon = "MAR";
                break;
            case 4:
                mon = "APR";
                break;
            case 5:
                mon = "MAY";
                break;
            case 6:
                mon = "JUN";
                break;
            case 7:
                mon = "JUL";
                break;
            case 8:
                mon = "AUG";
                break;
            case 9:
                mon = "SEPT";
                break;
            case 10:
                mon = "OCT";
                break;
            case 11:
                mon = "NOV";
                break;
            case 12:
                mon = "DEC";
                break;
        }
        String sDate = c.get(Calendar.DATE) + "-" + mon + "-" + c.get(Calendar.YEAR);
        date.setText(sDate);
        TextView months = (TextView) findViewById(R.id.textView8);
        months.setText(mon);

        if (t > high) {
            SQLiteDatabase dbn1 = openOrCreateDatabase("sample", MODE_PRIVATE, null);
            Cursor c111 = dbn1.rawQuery("select phno from user", null);
            c111.moveToFirst();
            if (c111 != null) {
                do {
                    int c12 = c111.getColumnIndex("phno");
                    final String phn = c111.getString(c12);
                    final int finalHigh = high;
                    AlertDialog.Builder a = new AlertDialog.Builder(this);
                    a.setTitle("Alert");
                    a.setMessage("The current temperature is " + t + " which is greater than the threshold value " + finalHigh);
                    a.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    a.show();
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            SmsManager sms = SmsManager.getDefault();
                            sms.sendTextMessage(phn, null, "The current temperature is " + t + " which is greater than the threshold value " + finalHigh,
                                    null, null);

                        }
                    }, 50000);

                    Toast.makeText(getApplicationContext(),
                            "Messages sent", Toast.LENGTH_SHORT).show();
                } while (c111.moveToNext());
            }
        }
        if (t < low) {
            SQLiteDatabase dbn1 = openOrCreateDatabase("sample", MODE_PRIVATE, null);
            Cursor c111 = dbn1.rawQuery("select phno from user", null);
            c111.moveToFirst();
            if (c111 != null) {
                do {
                    int c12 = c111.getColumnIndex("phno");
                    final String phn = c111.getString(c12);
                    final int finalHigh = high;
                    final int finalLow = low;
                    AlertDialog.Builder a = new AlertDialog.Builder(this);
                    a.setTitle("Alert");
                    a.setMessage("The current temperature is \" + t + \" which is lesser than the threshold value " + finalLow);
                    a.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    a.show();
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            SmsManager sms = SmsManager.getDefault();
                            sms.sendTextMessage(phn, null, "The current temperature is " + t + " which is lesser than the threshold value " + finalLow,
                                    null, null);

                        }
                    }, 50000);

                    Toast.makeText(getApplicationContext(),
                            "Messages sent", Toast.LENGTH_SHORT).show();
                } while (c111.moveToNext());
            }
        }
        Button b1 = (Button) findViewById(R.id.button2);
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AlertDialog.Builder alert = new AlertDialog.Builder(Dashboard.this);
                alert.setTitle("Choose");
                final String[] a = {"Temperature Log", "High Temperature", "Low Temperature"};
                alert.setItems(a, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub
                        if (a[arg1].equals("Temperature Log")) {

                            Intent in = new Intent(
                                    Dashboard.this, Templog.class);
                            //
                            //    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                            startActivity(in);
                            Dashboard.this.finish();

                        }
                        if (a[arg1].equals("High Temperature")) {


                            Intent i = new Intent(Dashboard.this, Highlog.class);
                            //      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                            startActivity(i);
                            Dashboard.this.finish();

// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        }
                        if (a[arg1].equals("Low Temperature")) {

                            Intent intent = new Intent(Dashboard.this, Lowlog.class);
                            startActivity(intent);
                            Dashboard.this.finish();

                        }


                    }
                });
                alert.show();
            }
        });
    }
}

2 个答案:

答案 0 :(得分:1)

A service is a component which runs in the background, without direct interaction with the user. As the service has no user interface it is not bound to the lifecycle of an activity. Services are used for repetitive and potential long running operations, checking for new data, data processing, indexing content, etc.

try to following Link :
[click][1]

[1]: https://github.com/codepath/android_guides/wiki/Starting-Background-Services

答案 1 :(得分:0)

使用服务在后台发送邮件。

服务是一种应用程序组件,可以在后台执行长时间运行的操作,但不提供用户界面。另一个应用程序组件可以启动服务,即使用户切换到另一个应用程序,它也将继续在后台运行。此外,组件可以绑定到服务以与其交互,甚至可以执行进程间通信(IPC)。

按照以下链接,它将帮助您

http://developer.android.com/guide/components/services.html