繁体   English   中英

Android-每1分钟发送一次Toast消息

[英]Android - Toast message every 1 minute

我正在尝试在Android中实现一项服务,该服务在Android中每1分钟显示一次敬酒消息。 我是Android开发的新手,并了解了AlarmManager,它将帮助我完成此任务。 我已经通过以下方式实现了代码:

这是我的IIManagerActivity类

package com.example.iimanager;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.widget.Toast;

public class IIManagerActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_iimanager);
        AlarmManager mgr=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Intent i=new Intent(this, SampleService.class);
        PendingIntent pi=PendingIntent.getService(this, 0, i, 0);
        mgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,  SystemClock.elapsedRealtime(), AlarmManager.INTERVAL_FIFTEEN_MINUTES/900, pi);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_iimanager, menu);
        return true;
    }
}

这是我的SampleService,用于显示敬酒消息。 由于某种原因,无论等待多长时间,我都看不到吐司消息。

package com.example.iimanager;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class SampleService extends IntentService {

    public SampleService() {
        super("SimpleService");
        //Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
         //do something
        Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
    }
}

您能告诉我什么地方出了问题,需要做什么来纠正它?

提前非常感谢您。

复制以下3行以进行敬酒

计时器计时器=新的计时器();
TimerTask updateProfile =新的SampleService(SampleService.this); timer.scheduleAtFixedRate(updateProfile,10,1000);

class CustomTimerTask extends TimerTask {
private Context context;
private Handler mHandler = new Handler();
        // Write Custom Constructor to pass Context
    public CustomTimerTask(Context con) {
        this.context = con;
    }

    @Override
    public void run() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            mHandler.post(new Runnable() {
            @Override
            public void run() {
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();    
        }
    });
}
}).start();

}

    }

尝试创建一个Timer对象,然后使用scheduleAtFixedRate(TimerTask)重复Toast消息。

尝试以下代码,

MainActivity.java

public class MyService extends Service {

public static final long INTERVAL=60000;//variable for execute services every 1 minute
private Handler mHandler=new Handler(); // run on another Thread to avoid crash
private Timer mTimer=null; // timer handling

@Nullable
@Override
public IBinder onBind(Intent intent) {
    throw new UnsupportedOperationException("unsupported Operation");
}
@Override
public void onCreate() {
    // cancel if service is  already existed
        if(mTimer!=null)
            mTimer.cancel();
    else
            mTimer=new Timer(); // recreate new timer
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(),0,INTERVAL);// schedule task
}
@Override
public void onDestroy() {
    Toast.makeText(this, "In Destroy", Toast.LENGTH_SHORT).show();//display toast when method called
    mTimer.cancel();//cancel the timer
}
//inner class of TimeDisplayTimerTask
private class TimeDisplayTimerTask extends TimerTask {
    @Override
    public void run() {
        // run on another thread
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // display toast at every 1 minute
                Toast.makeText(getApplicationContext(), "Notify", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);//load the layout file
    startService(new Intent(this,MyService.class));//use to start the services
}
}

还要将此代码添加到清单文件中

AndroidManifest.xml

<service android:name=".MyService"
        android:enabled="true"/>

您可以只创建一个包含代码的循环线程。

像这样:

public class Toaster extends Thread{                      
    public void run(){              
    //Your code to loop

    thread.sleep(60000)           
         }
    }

希望能帮助到你!

暂无
暂无

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

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