我遇到的问题是,当时间更改时,应用程序运行时仅调用TIME_TICK。但即使应用正在运行或未使用广播接收器,我也希望得到它。
主要活动
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(), "Checking", Toast.LENGTH_LONG).show();
}
}
MyBroadastReceivers
public class MyBroadastReceiversextends BroadcastReceiver
{
@Override
public void onReceive(Context arg0, Intent arg1) {
Toast.makeText(arg0, "Toast Receive", Toast.LENGTH_LONG).show();
}
}
清单文件
<receiver android:name="com.example.serviceschecking.MyBroadastReceivers" android:enabled="true" android:exported="true">
<intent-filter >
<action android:name="android.intent.action.TIME_TICK"/>
</intent-filter>
</receiver>
答案 0 :(得分:4)
如API所述您必须以编程方式注册此意图:
广播行动:当前时间已经改变。每分钟发送一次。您 不能通过清单中声明的组件来接收这个,只能通过 使用Context.registerReceiver()显式注册它。
你必须在你的mainActivity中注册它:
IntentFilter mTime = new IntentFilter(Intent.ACTION_TIME_TICK);
registerReceiver(YourReceiver, mTime);
答案 1 :(得分:2)
&#34;您无法通过清单中声明的组件接收此信息,只能通过使用Context.registerReceiver()&#34;显式注册它。
查看代码,例如:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(), "Checking", Toast.LENGTH_LONG).show();
receiver = new MyBroadastReceivers();
registerReceiver(receiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
@Override
protected void onDestroy() {
// Unregister MyBroadastReceivers
unregisterReceiver(receiver);
}
}
另外,根据您的想法,AlarmManager可能是一个很好的选择,特别是如果您让用户配置轮询频率&#34;。请查看此SO thread。
答案 2 :(得分:-1)
PErfact示例我已经过测试和工作
package com.sifat.githubalarmapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I am running sifat", Toast.LENGTH_LONG).show();
}
}
package com.sifat.githubalarmapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
}
添加清单
<!-- Will not be called unless the application explicitly enables it -->
<receiver android:name=".AlarmReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_TIME_TICK"/>
</intent-filter>
</receiver>