报警服务接收器android

时间:2016-02-11 12:25:51

标签: java android

public class MyBroadcastReceiver  extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Calendar c = Calendar.getInstance();
        hour=c.get(Calendar.HOUR_OF_DAY);
        minute=c.get(Calendar.MINUTE);
        Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
        String date = sdf.format(calendar.getTime());
        String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);
        minochaDevicePolicyManager.resetPassword(str,0);
    }
}

嘿伙计们,所以这里的问题是我需要为这个接收器创建一个类,我不知道如何这样做。我需要将它与我的主活动类链接,因为变量在那里(ex minochaDevicePolicyManager)。怎么做是的,我试图在网上查找,我想出了这个网站,但它并没有真正的帮助。 怎么办? 这是主要活动中的警报服务 - >的onCreate

Context context=getApplicationContext();
    alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, MyBroadcastReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            1000 * 60, alarmIntent);

现在该怎么做。我需要一个接收器类,它必须链接到主要活动

2 个答案:

答案 0 :(得分:0)

您需要MainActivity和MyBroadcastReceiver都提供单个对象。

添加新的 App.java 类,如下所示

package ....;

import android.app.Application;

public class App extends Application {
    public DevicePolicyManager minochaDevicePolicyManager;

    @Override
    public void onCreate() {
        super.onCreate();

        minochaDevicePolicyManager = (DevicePolicyManager)getSystemService(Context.DEVICE_‌​POLICY_SERVICE);
    }
}

然后修改您的AndroidManifest.xml以引用App类

<application
    android:name="App" ...>

然后,当您要使用DevicePolicyManager实例时,在MainActivity和MyBroadcastReceiver中执行以下操作;

在两个类的顶部添加一个成员变量

private fullpackagename.App app;

使用以下

在MainActivity OnCreate和MyBroadcastReceiver OnReceive方法中获取对它的引用
this.app = ((App) getApplicationContext());

要使用该实例,请参阅app.minochaDevicePolicyManager

app.minochaDevicePolicyManager.resetPassword(str,0);

答案 1 :(得分:0)

即使您要求对minochaDevicePolicyManager进行一次引用,因为我猜测您没有使用它,但经常没有理由您不能创建新实例使用传入的context在MyBroadcastReceiver中。

public class MyBroadcastReceiver  extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Calendar c = Calendar.getInstance();
        hour=c.get(Calendar.HOUR_OF_DAY);
        minute=c.get(Calendar.MINUTE);
        Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
        String date = sdf.format(calendar.getTime());
        String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);

        DevicePolicyManager minochaDevicePolicyManager = (DevicePolicyManager)context.getSystemService(Context.DEVICE_‌​POLICY_SERVICE);

        minochaDevicePolicyManager.resetPassword(str,0);
    }
}