2

我正在尝试在 Android 中实现一项服务,该服务在 Android 中每 1 分钟显示一条 toast 消息。我是 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();
    }
}

你能告诉我哪里出了问题以及需要做些什么来纠正它吗?

非常感谢您提前。

4

4 回答 4

1

复制以下 3 行用于 toast 调用

定时器 timer = new Timer();
TimerTask updateProfile = new 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();

}

    }
于 2013-04-02T02:47:33.550 回答
1

试试下面的代码,

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"/>
于 2016-12-28T10:36:01.907 回答
0

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

于 2013-04-02T02:12:01.190 回答
-2

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

像这样:

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

    thread.sleep(60000)           
         }
    }

希望能帮助到你!

于 2013-04-02T00:47:08.980 回答