- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - phát hiện rò rỉ bộ nhớ Ruby/Ruby on Rails
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我希望我的应用程序在单击按钮时启动服务,并且服务应该在后台运行以在一天中的特定时间显示通知。我有以下代码来执行此操作。但它显示了我不明白的错误。我是 Android 新手,这是我第一个使用 Service 的应用程序。任何帮助,将不胜感激。提前致谢。
AndroidManifest.xml
package="com.example.newtrial"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<ứng>ứng>
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/tên_ứng_dụng"
android:theme="@style/AppTheme" >
android:name="com.example.newtrial.CreateNotificationActiviy"
android:label="@string/tên_ứng_dụng" >
android:name="com.example.newtrial.ResultActivity"
android:label="@string/title_activity_result" >
CreateNotificationActiviy.java
package com.example.newtrial;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class CreateNotificationActiviy extends Activity {
@Ghi đè
được bảo vệ void onCreate(Gói savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_notification_activiy);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
@Ghi đè
public void onClick(View v) {
// TODO Phương thức tự động tạo stub
startService(new Intent(CreateNotificationActiviy.this, UpdaterServiceManager.class));
}
});
}
public void createNotification(View view) {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, ResultActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Build notification
// Actions are just fake
Notification noti = new Notification.Builder(this)
.setContentTitle("Notification Title")
.setContentText("Click here to read").setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.xây dựng();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
}
@Ghi đè
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_notification_activiy, menu);
trả về giá trị đúng;
}
}
UpdaterServiceManager.java
package com.example.newtrial;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
public class UpdaterServiceManager extends Service {
private final int UPDATE_INTERVAL = 60 * 1000;
private Timer timer = new Timer();
private static final int NOTIFICATION_EX = 1;
private NotificationManager notificationManager;
CreateNotificationActiviy not;
public UpdaterServiceManager() {
not=new CreateNotificationActiviy();
}
@Ghi đè
public IBinder onBind(Intent intent) {
// TODO Phương thức tự động tạo stub
trả về giá trị null;
}
@Ghi đè
public void onCreate() {
// code to execute when the service is first created
super.onCreate();
Log.i("MyService", "Service Started.");
showNotification();
}
public void showNotification()
{
final Calendar cld = Calendar.getInstance();
int time = cld.get(Calendar.HOUR_OF_DAY);
if(time>12)
{
not.createNotification(null);
}
khác
{
AlertDialog.Builder alert=new AlertDialog.Builder(this);
alert.setMessage("Not yet");
alert.setTitle("Error");
alert.setPositiveButton("OK", null);
alert.create().show();
}
}
@Ghi đè
public void onDestroy() {
if (timer != null) {
timer. hủy();
}
}
@Ghi đè
public int onStartCommand(Intent intent, int flags, int startid)
{
return START_STICKY;
}
private void stopService() {
if (timer != null) timer.cancel();
}
}
ResultActivity.java
package com.example.newtrial;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class ResultActivity extends Activity {
@Ghi đè
được bảo vệ void onCreate(Gói savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText("After notification is clicked" );
}
@Ghi đè
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.result, menu);
trả về giá trị đúng;
}
}
Logcat
12-10 12:14:04.286: I/Process(872): Sending signal. PID: 872 SIG: 9
12-10 12:14:11.774: I/MyService(893): Service Started.
12-10 12:14:12.094: D/AndroidRuntime(893): Shutting down VM
12-10 12:14:12.094: W/dalvikvm(893): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
12-10 12:14:12.124: E/AndroidRuntime(893): FATAL EXCEPTION: main
12-10 12:14:12.124: E/AndroidRuntime(893): java.lang.RuntimeException: Unable to create service com.example.newtrial.UpdaterServiceManager: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
12-10 12:14:12.124: E/AndroidRuntime(893): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2587)
12-10 12:14:12.124: E/AndroidRuntime(893): at android.app.ActivityThread.access$1600(ActivityThread.java:141)
12-10 12:14:12.124: E/AndroidRuntime(893): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1338)
12-10 12:14:12.124: E/AndroidRuntime(893): at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 12:14:12.124: E/AndroidRuntime(893): at android.os.Looper.loop(Looper.java:137)
12-10 12:14:12.124: E/AndroidRuntime(893): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-10 12:14:12.124: E/AndroidRuntime(893): at java.lang.reflect.Method.invokeNative(Native Method)
12-10 12:14:12.124: E/AndroidRuntime(893): at java.lang.reflect.Method.invoke(Method.java:525)
12-10 12:14:12.124: E/AndroidRuntime(893): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-10 12:14:12.124: E/AndroidRuntime(893): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-10 12:14:12.124: E/AndroidRuntime(893): at dalvik.system.NativeStart.main(Native Method)
12-10 12:14:12.124: E/AndroidRuntime(893): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
12-10 12:14:12.124: E/AndroidRuntime(893): at android.view.ViewRootImpl.setView(ViewRootImpl.java:563)
12-10 12:14:12.124: E/AndroidRuntime(893): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:269)
12-10 12:14:12.124: E/AndroidRuntime(893): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
12-10 12:14:12.124: E/AndroidRuntime(893): at android.app.Dialog.show(Dialog.java:281)
12-10 12:14:12.124: E/AndroidRuntime(893): at com.example.newtrial.UpdaterServiceManager.showNotification(UpdaterServiceManager.java:65)
12-10 12:14:12.124: E/AndroidRuntime(893): at com.example.newtrial.UpdaterServiceManager.onCreate(UpdaterServiceManager.java:41)
12-10 12:14:12.124: E/AndroidRuntime(893): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2577)
12-10 12:14:12.124: E/AndroidRuntime(893): ... 10 more
câu trả lời hay nhất
这个问题比较老了,但我希望这篇文章仍然可能对其他人有用。
TL;DR:使用AlarmManager调度任务,使用IntentService,见示例代码đây ;
简单的 helloworld 应用,每 2 小时向您发送一次通知。单击通知 - 在应用程序中打开辅助 Activity ;删除通知轨道。
一旦您需要按计划运行某些任务。我自己的案例:每天一次,我想从服务器获取新内容,根据我获得的内容编写通知并将其显示给用户。
首先,我们创建2个activity:MainActivity,启动notification-service和NotificationActivity,通过点击通知启动:
activity_main.xml
android:layout_width="phù hợp với cha mẹ"
android:layout_height="match_parent"
android:padding="16dp">
<>
android:id="@+id/sendNotifications"
android:onClick="onSendNotificationsButtonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Sending Notifications Every 2 Hours!" />
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Ghi đè
được bảo vệ void onCreate(Gói savedInstanceState) {
super.onCreate(savedInstanceState);
thiết lậpContentView(R.layout.activity_main);
}
public void onSendNotificationsButtonClick(View view) {
NotificationEventReceiver.setupAlarm(getApplicationContext());
}
}
NotificationActivity 是您可以想出的任何随机 Activity 。 注意!不要忘记将这两个 Activity 都添加到 AndroidManifest 中。
然后我们创建 WakefulBroadcastReceiver
广播接收器,我在上面的代码中调用了 NotificationEventReceiver。
在这里,我们将设置 AlarmManager
开火PendingIntent
每 2 小时(或以任何其他频率),并在 onReceive()
中指定此 Intent 的已处理操作方法。在我们的例子中 - 清醒地 开始 IntentService
,我们将在后面的步骤中指定。这个IntentService
会为我们生成通知。
此外,此接收器将包含一些辅助方法,例如创建 PendintIntents,我们稍后将使用这些方法
NB1! 因为我正在使用 WakefulBroadcastReceiver
,我需要在 list 中添加额外权限:
NB2! 我使用它是广播接收器的唤醒版本,因为我想确保设备在我的 IntentService
期间不会重新进入休眠状态。的操作。在 hello-world 中,这并不重要(我们的服务中没有长时间运行的操作,但想象一下,如果在此操作期间您必须从服务器获取一些相对较大的文件)。阅读有关设备唤醒的更多信息 đây .
NotificationEventReceiver.java
public class NotificationEventReceiver extends WakefulBroadcastReceiver {
private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
public static void setupAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = getStartPendingIntent(context);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
getTriggerAt(new Date()),
NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
alarmIntent);
}
@Ghi đè
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Intent serviceIntent = null;
if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
} else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
}
if (serviceIntent != null) {
startWakefulService(context, serviceIntent);
}
}
private static long getTriggerAt(Date now) {
Lịch lịch = Calendar.getInstance();
calendar.setTime(now);
//calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
return calendar.getTimeInMillis();
}
private static PendingIntent getStartPendingIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static PendingIntent getDeleteIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_DELETE_NOTIFICATION);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
现在让我们创建一个 IntentService
实际创建通知。
在那里,我们指定 onHandleIntent()
这是对我们在 startWakefulService
中传递的 NotificationEventReceiver Intent 的响应方法。
如果是删除操作 - 例如,我们可以将其记录到我们的分析中。如果是开始通知 Intent - 然后使用 NotificationCompat.Builder
我们正在编写新的通知并通过 NotificationManager.notify
显示它.在撰写通知时,我们还为点击和删除操作设置待处理的 Intent 。相当容易。
NotificationIntentService.java
public class NotificationIntentService extends IntentService {
private static final int NOTIFICATION_ID = 1;
private static final String ACTION_START = "ACTION_START";
private static final String ACTION_DELETE = "ACTION_DELETE";
public NotificationIntentService() {
super(NotificationIntentService.class.getSimpleName());
}
public static Intent createIntentStartNotificationService(Context context) {
Intent intent = new Intent(context, NotificationIntentService.class);
intent.setAction(ACTION_START);
return intent;
}
public static Intent createIntentDeleteNotification(Context context) {
Intent intent = new Intent(context, NotificationIntentService.class);
intent.setAction(ACTION_DELETE);
return intent;
}
@Ghi đè
protected void onHandleIntent(Intent intent) {
Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
thử {
String action = intent.getAction();
if (ACTION_START.equals(action)) {
processStartNotification();
}
if (ACTION_DELETE.equals(action)) {
processDeleteNotification(intent);
}
} Cuối cùng {
WakefulBroadcastReceiver.completeWakefulIntent(intent);
}
}
private void processDeleteNotification(Intent intent) {
// Log something?
}
private void processStartNotification() {
// Do something. For example, fetch fresh data from backend to create a rich notification?
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Scheduled Notification")
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.colorAccent))
.setContentText("This notification has been triggered by Notification Service")
.setSmallIcon(R.drawable.notification_icon);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
NOTIFICATION_ID,
new Intent(this, NotificationActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, builder.build());
}
}
快完成了。现在,我还为 BOOT_COMPLETED、TIMEZONE_CHANGED 和 TIME_SET 事件添加广播接收器,以在设备重新启动或时区更改后重新设置我的 AlarmManager(例如,用户从美国飞往欧洲并且您不希望弹出通知在半夜,但对本地时间很敏感:-))。
NotificationServiceStarterReceiver.java
public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
@Ghi đè
public void onReceive(Context context, Intent intent) {
NotificationEventReceiver.setupAlarm(context);
}
}
我们还需要在 AndroidManifest 中注册我们所有的服务、广播接收器:
package="klogi.com.notificationbyschedule">
<ứng>ứng>
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/tên_ứng_dụng"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<>
android:name=".notifications.NotificationIntentService"
android:enabled="true"
android:exported="false" />
android:name=".NotificationActivity"
android:label="@string/title_activity_notification"
android:theme="@style/AppTheme.NoActionBar"/>
这个项目的源代码你可以找到đây .希望这篇文章对您有所帮助。
关于android - 使用 Service 运行后台并创建通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20501225/
Tôi tìm trên mạng nhưng không tìm thấy bài viết phù hợp giải thích cách sử dụng dịch vụ WCF bằng javascript, đặc biệt là WebScriptEndpoint. Bất cứ ai có thể đưa ra bất kỳ hướng dẫn về điều này? Cảm ơn bạn vì câu trả lời tốt nhất Đây là một bài viết về.
Tôi đang viết một chương trình C sẽ chạy các lệnh Linux, ví dụ: cat /etc/passwd | grep list cut -c 1-5 Tôi không nhận được kết quả nào *ở đây cha mẹ đợi con đầu lòng (chi
Vì vậy, tôi đang cố gắng xử lý việc tải tệp lên và sau đó lưu trữ tệp đó vào cơ sở dữ liệu dưới dạng tệp nhị phân. Sau khi lưu trữ, tôi cố gắng phân phát tệp trên URL đã cho. Tôi dường như không thể tìm thấy một phương pháp hoạt động ở đây. Tôi cần sử dụng cơ sở dữ liệu vì tôi sử dụng Google Apps
Tôi đang cố gắng tạo một macro thêm công thức bên dưới vào một ô rồi kéo nó qua cột và sao chép cùng một công thức trong cột H. Tôi muốn nhập dữ liệu vào cột F và H bằng công thức Range("F1") .công thức = "=IF(ISE
Câu hỏi tương tự như câu hỏi này, nhưng tôi muốn sử dụng OperatorPrecedenceParser để phân tích một biểu thức bằng ứng dụng hàm trong FParsec. Đây là AST của tôi: type Expression =.
Tôi muốn thay đổi truy vấn này thành mã tùy thuộc vào vị trí chọn COUNT(giới tính) làm số lượng giới tính từ khách hàng bằng cách sử dụng phần tiếp theo và node.js
Tôi đang sử dụng GNU bash, phiên bản 5.0.3(1)-distro (x86_64-pc-linux-gnu) và tôi đang tự hỏi tại sao tôi lại gặp lỗi cú pháp với một câu lệnh gán đơn giản: #/bin/bash var1= /tmp
Đây là lý do tại sao mã của tôi không hoạt động trong IE. Mã của tôi hoạt động trong tất cả các trình duyệt. Không có gì. Nhưng khi tôi chạy dự án của mình trên IE thì nó phát hiện lỗi. Và cả lớp jquery của tôi cũng như lớp InsertadjacentHTMl đều không
Tôi đang cố gắng thay đổi HTML bên trong của thẻ. Tôi không có quyền truy cập vào biểu mẫu nên không thể chỉnh sửa HTML. Mã định danh duy nhất mà thẻ có là thuộc tính "for". Đây là cấu trúc của đầu vào và nhãn:
Tôi có một trang nơi tôi trả lại bài đăng của người dùng, tôi có thể đưa ra nhận xét ngay lập tức về những bài đăng này bằng cách sử dụng một số mã jquery, sau khi nhận xét mới được đăng, tôi chèn nhận xét mới bên dưới bài đăng cùng với nút xóa. Vấn đề là nút Xóa không hoạt động trên các phần tử mới được chèn vào,
Tôi có tệp "được phân cách bằng đường ống" với khoảng 20 cột. Tôi chỉ muốn băm cột đầu tiên bằng cách sử dụng sha1sum, một số giống như số tài khoản và trả về phần còn lại của các cột. Cách tốt nhất để làm điều này bằng awk hoặc sed là gì? tài khoản
Tôi cần chèn nội dung sau vào bảng của mình... Bảng người dùng của tôi có năm cột id, tên người dùng, mật khẩu, tên, mục nhập. (Tôi chưa gửi bất cứ thứ gì vào mục này, tôi sẽ làm điều đó sau bằng php) Nhưng vì lý do nào đó tôi vẫn gặp lỗi này: #1054 - U
Vì vậy, tôi đang cố gắng có một trường nhập để tôi có thể nhập bất kỳ ký tự nào, nhưng sau đó viết thường giá trị đã nhập, xóa mọi ký tự không phải chữ và số, để lại "." Ví dụ mình nhập: 70% trái đất là nước, -!*#$^ & 30% đất bị mất
Tôi đang cố gắng làm một việc mà tôi nghĩ là rất đơn giản nhưng vì lý do nào đó tôi lại không đạt được kết quả như mong muốn? Tôi mới làm quen với javascript nhưng có kinh nghiệm với java nên tôi tin rằng mình không sử dụng một số loại quy tắc chính xác. Đây là phương thức lấy giá trị đầu vào, kiểm tra lựa chọn
Tôi muốn tải dữ liệu từ cơ sở dữ liệu mysql bằng Angularjs. Đây là cách ứng dụng hoạt động; người dùng đăng nhập và tên người dùng của họ được lưu trữ trong cookie. Tên người dùng này được hiển thị trên trang chủ. Tôi muốn nhận giá trị này và chuyển nó qua Angularjs
Tôi đang sử dụng autoLayout và tôi muốn đặt nhãn UIlabel trên UITableViewCell, nhãn này phải luôn ở bên phải và chính giữa phía bên phải của ô. Đây là điều tôi đang cố gắng đạt được nên ở đây bạn có thể thấy điều tôi đang nói đến
Tôi cần truy vấn tương đương với elaticsearch với MySql. Truy vấn sql của tôi: CHỌN DISTINCT t.product_id NHƯ id TỪ tbl_sup_price t
Tôi đang triển khai mã để sử dụng JSON. thiết lập func() { if let FlickrURL = NSURL(string: "https://api.flickr.com/
Tôi đã thử khai báo một biến bằng vòng lặp for và sau đó kiểm tra xem cols và rols có giống nhau không. Nếu có, nó sẽ chạy hàm đệ quy. Tuy nhiên, tôi gặp sự cố khi thực hiện thao tác trong javascript. Có ai có thể giúp được không? Bây giờ, khi so sánh col.1 và
Tôi đã đưa ra một ví dụ ngắn gọn về vấn đề tôi đang giải quyết. Mã HTML: 1 2 3 Mã CSS: .BB a:hover{ color: #000 } .BB > li:after {
Tôi là một lập trình viên xuất sắc, rất giỏi!