我知道android workmanager,但我不知道如何使用它

时间:2018-06-23 17:00:58

标签: android worker notify

我有一个应用程序,可在设备连接到互联网时通知用户。我使用workmanager,它工作正常,但仅当应用程序正在运行时!

它应该在人们未连接互联网时通知他们!怎么才能做到这一点!?

这是我的第一个活动:

public class WorkActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_work);

    Intent intent = new Intent();
    PendingIntent pendingIntent = PendingIntent.getActivity(WorkActivity.this,0,intent,0);
    Constraints constraints = new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build();
    NotifyWorker.pendingIntent = pendingIntent;
    NotifyWorker.context = this;
    OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(NotifyWorker.class).setConstraints(constraints).build();
    WorkManager workManager = WorkManager.getInstance();
    workManager.enqueue(oneTimeWorkRequest);

}

}

这是我的工人班:

public class NotifyWorker extends Worker {

public static Context context;
public static PendingIntent pendingIntent;

@NonNull
@Override
public Result doWork() {
    Log.i("wd","wd");

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context,"con")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.mipmap.ic_launcher))
            .setSmallIcon(R.drawable.logo)
            .setContentTitle("Title")
            .setContentText("Desc")
            .setContentIntent(pendingIntent);

    android.app.NotificationManager notificationManager =
            (android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 , notificationBuilder.build());

    return Result.SUCCESS;
}

}

我很困惑:/请帮忙!

0 个答案:

没有答案
相关问题